Smart pointer question

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.

Answers


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.


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_ptrs that both control the same object but where one is not a copy of the other.


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);

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.


Need Your Help

Get contents of Java Swing Component

java swing

I need to get contents of JPanel component (one of tabs), which a part of JTabbedPane. From class where JTabbedPane is defined there is an event listener which gets current selected tab (on state

C# - Loading methods within the constructor

c# .net windows constructor

Could someone explain why executing this method (in the constructor) throws a syntax error:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.