"Just use a GC" is a viable answer to this in many circumstances, but probably not all.
"Just use a GC" is a viable answer to this in many circumstances, but probably not all.
Imagine you return a reference-counted pointer from a function. Then every call to this function is a lock/unlock and CPU cache synchronization. And if the pointed object is shared between threads (even for read-only access) this might lead to lot of contended locks/unlocks, which is extremely costly.
If you have a std::shared_ptr<X>, then most of the time you will be passing around "X &" or "std::shared_ptr<X> &" and no copies will happen.
Do you have an example of why a function would be returning a std::shared_ptr<X> by value that wasn't a move?
As of using naked references, you're right, but if you can use naked references, why ever use shared_ptr? Naked references are fine when you know the lifetime of the object.
Don't get me wrong - shared pointers are useful in many scenarios, but they are not a general replacement for GC.
shared_ptr took 17% of time. This is far beyond what GC takes even in a very memory heavy Java application (typically GC stays below 1% overhead).
I'm not saying you shouldn't use shared_ptr at all, but only: be careful.
Therefore a relatively simple operation like pointer assignment can be one cycle when using GC and a hundred to several thousands cycles when using refcounting. Sometimes you can ignore this overhead, sometimes not - depends on how often you do that.
http://software.intel.com/en-us/articles/choosing-between-sy...