9 ms·
The synchronization you mention is really rare, it only happens when you make a copy (not a move!) of a std::shared_ptr. If you have a std::shared_ptr<X>, then
by detrino 13y ago
The synchronization you mention is really rare, it only happens when you make a copy (not a move!) of a std::shared_ptr.
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?
- pkolaczk 13y agoTo return a shared_ptr you first had to create it. So even if it optimizes the move, it doesn't optimize away the creation of the pointer and its destruction. 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.
- pkolaczk 13y agoBTW: Here is the post of someone who thought he can use shared_ptr as a poor-man's GC: http://stackoverflow.com/questions/2502394/the-cost-of-passing-by-shared-ptr http://stackoverflow.com/questions/2502394/the-cost-of-passi... 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.
- detrino 13y agoNovices also sometimes erroneously pass std::vector by value, that doesn't mean std::vector is slow. Maybe you did not read the entire post before linking it. The conclusion was he changed his code to pass by reference and 17.77% became .27%.
- eliasmacpherson 13y agoThanks for pointing that out, I had heard horror stories before and was willing to take 17.77% at face value!
- detrino 13y agoYou can use naked references because most functions aren't acquiring ownership of a shared_ptr.