I have a project and I want make smart pointers usage better.
The main idea is to use them when returning new object from function. The question is what smart pointer to use? auto_ptr or shared_ptr from boost? As I know, auto_ptr is slower but it can fall back to the ‘pure’ pointer.
And if I’ll use smart pointer in place where I don’t need it, would it make the perfomance slower?
What makes you think
auto_ptris slower thanshared_ptr? Typically I would expect the reverse to be true, sinceshared_ptrneeds to update the reference count.As for which you should use, different smart pointers imply different ownership semantics. Ownership implies the responsibility to delete the object when it is no longer needed.
scoped_ptrimplies single (ie, non-shared), non-transferable ownership.auto_ptrimplies single (ie, non-shared) transferable ownership. This is the smart pointer I would use to return a newly constructed object from a function (the function is transferring the object to its caller).auto_ptrsuffers from the disadvantage that due to limitations of the language whenauto_ptrwas defined, it is difficult to use correctly (this has given it a very bad reputation, though the intended purpose of a smart pointer with single, transferable ownership semantics was and is both valid and useful).unique_ptrhas the same semantics asauto_ptr, but uses new C++0x features (rvalue references) to make it a lot safer (less prone to incorrect use) thanauto_ptr. If you are developing on a platform whereunique_ptris available, then you should use it instead ofauto_ptr.shared_ptrimplies shared ownership. In my opinion this is over-used. It does have many valid uses, but it should not simply be used as a default option.I would also add that
shared_ptris often used with STL containers because the other smart pointer classes do not achieve their intended function in that context (due to copying of values internally within the container). This often leads to use ofshared_ptrwhere shared ownership is not really the intended meaning. In these cases, I suggest (where possible) using the boost pointer-container classes (ptr_vector,ptr_mapand so on), which provide the (commonly desired) semantics of a container with transferable, but single (non-shared) ownership.You should always think about the ownership of your objects: in most cases, with a clean system design, each object has one obvious owner, and ownership does not need to be shared. This has the advantage that it is easy to see exactly where and when objects will be freed, and no reference counting overhead is needed.
[edited to note the new
unique_ptr]