Reputation: 64266
I'm rewriting my code with smart pointer. I have such situation:
void Foo(SomeClass *p) { }
boost::shared_ptr<SomeClass> p(new SomeClass);
Now what to do: pass original pointer from wrapper (p.get()
) or rewrite function argument and pass smart pointer directly like:
void Foo(boost::shared_ptr<Foo> obj) { }
I'm not sure. As I understand smart pointers should follow some pointer and look whether it still need in program. So we can pass original pointer.
Upvotes: 4
Views: 550
Reputation: 18507
Would the parameter to Foo
ever be null? If the answer is no, then you really should use a reference instead of a pointer:
void Foo(SomeClass &obj) { }
Usage:
boost::shared_ptr<SomeClass> obj(new SomeClass);
Foo(*obj);
Upvotes: 2
Reputation: 15758
If you are already rewriting your code to use smart pointers, then you should go all the way and remove the plain/raw pointers wherever that is possible.
Smart pointers do not employ some magic to keep track of their contents (like a Garbage Collector does), but they use a rather simple heuristic to determine if the object they control should be released or not. Incorrect use of smart pointers can easily break this heuristic.
For example, shared_ptr
keeps track of all the copies that are made (directly or indirectly as copies from copies) and destroys the controlled object when the last copy is being destroyed.
This breaks horribly if you manage to create two shared_ptr
s that both control the same object but where one is not a copy of the other.
Upvotes: 3
Reputation: 8221
If your function only uses the pointer p to manipulate or read the SomeClass object, you can go with p.get(). If your pointer p is assigned to some other pointer variable or similar, you should change the signature of the function.
Upvotes: 0
Reputation: 791371
Unless Foo
needs to take (shared) ownership of *p
you should keep the signature the same and just pass p.get()
. It's the simplest and most flexible option as well as requiring the least change to your existing code.
Upvotes: 5