Smart pointer

I am rewriting my code with a smart pointer. I have this situation:

void Foo(SomeClass *p) { } boost::shared_ptr<SomeClass> p(new SomeClass); 

Now what to do: pass the original pointer from the shell ( p.get() ) or rewrite the argument of the function and pass the smart pointer directly like this:

 void Foo(boost::shared_ptr<Foo> obj) { } 

I'm not sure. As far as I understand, smart pointers should follow the pointer and see what is still needed in the program. Therefore, we can pass the original pointer.

+4
source share
4 answers

If Foo needs to take (shared) ownership of *p , you must leave the signature the same and just go through p.get() . This is the easiest and most flexible option, as well as minimal modification to existing code.

+5
source

If you are already rewriting your code to use smart pointers, you should go all the way and remove simple / raw pointers where possible.

Smart pointers do not use some magic to track their contents (e.g. garbage collector), but they use fairly simple heuristics to determine if the released object should be released or not. The misuse of smart pointers can easily break this heuristic.

For example, shared_ptr keeps track of all copies that are made (directly or indirectly, like copies from copies) and destroys the monitored object when the last copy is destroyed. This breaks down terribly if you manage to create two shared_ptr that manage the same object, but where it is not a copy of the other.

+3
source

Will the Foo parameter ever be null? If the answer is no, then you really should use the link instead of the pointer:

 void Foo(SomeClass &obj) { } 

Using:

 boost::shared_ptr<SomeClass> obj(new SomeClass); Foo(*obj); 
+2
source

If your function uses only the p pointer to control or read the SomeClass object, you can go to p.get (). If your pointer p is assigned to some other pointer variable or similar, you must change the signature of the function.

0
source

Source: https://habr.com/ru/post/1333681/