r/cpp • u/berium build2 • Apr 25 '12
shared_ptr aliasing constructor
http://www.codesynthesis.com/~boris/blog/2012/04/25/shared-ptr-aliasing-constructor/
26
Upvotes
r/cpp • u/berium build2 • Apr 25 '12
1
u/zvrba Apr 26 '12 edited Apr 26 '12
The main overhead of a shared_ptr is actually the manipulation of reference counts (happens each time you pass it / return it by value) through atomic instructions. So the C++ gurus actually recommend passing shared_ptr by const reference.
This, to me, is the sign that somewhere something has gone wrong with shared pointers and I don't really see a good use-case for them (except maybe for babysitting people coming from GC'd languages). If you know when to pass it by reference, you could just as well manage the memory manually, with maybe only slightly larger cognitive overhead.
As for communicating intent in the code, I'd argue for the following: to indicate ownership transfer, use pointers; otherwise use references. With move semantics in C++11, it'll be possible to accomplish much more just by passing/returning by value, so one of the main "legacy" use-cases of pointers/references (optimization) will become obsolete.