Search code examples
c++shared-ptrdouble-pointer

Null checking from multiple sources: shared_ptr vs double pointer?


Need to null check cached pointer from multiple sources, like so:

double pointer:

int *ptr = new int(10); 
int **pptr = &ptr; // from another source
ptr = nullptr;
cout << *pptr << endl; //nullptr

shared_ptr:

shared_ptr<int> sptr = make_shared<int>(10); 
weak_ptr<int> wptr = sptr; //from another source
sptr.reset();
cout << wptr.lock() << endl; //nullptr

Concerns:

I'm not especially fond of the double pointer syntax not to mention it can be unsafe, but I keep hearing that shared_ptr is really slow due to reference counting which I don't really need because only one source is supposed to be in charge of object scope. Is the loss of whatever performance worth it with managed memory?

Preferably, are there any alternatives to either of these?


Solution

  • First of all, pre optimization is the root of all evil and you should NOT spare some of the best features in a programming language because you are afraid of minor performance penalty!

    Now that we have this issue out of our way, I'll recommend you use managed objects as much as possible and if and when performance becomes an issue use an actual benchmarking tool to find your bottlenecks...

    Regarding your actual problem, It is not clear enough what you are doing with your pointer so its hard to suggest alternatives, but I'd recommend taking a look at this link for a comprehensive description of smart pointers in the standard library.