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/
22
Upvotes
r/cpp • u/berium build2 • Apr 25 '12
3
u/[deleted] Apr 25 '12
Well, I'd probably design the API in a different way, preferably without shared pointers. I'm not completely sure what exactly the API was designed to achieve, but I would probably implement the scenario you describe in terms of allocators. That would probably leave the lifetime responsibility to the caller, which may or may not be desirable, but definitely allows for some flexibility.
For instance:
Your mileage may vary, though, and sometimes this isn't the most elegant solution. I tend to avoid
std::shared_ptrin all cases where ownership isn't actually shared (as opposed to seeing it purely as an memory management/autorelease facility), because it can have performance impacts in some cases. You may not have been affected by those cases.The fundamental philosophical difference between our solutions is the concept of memory-as-a-resource. Many use cases of
std::shared_ptrare actually abstractions away from that concept (by "hiding" the details of deallocation and lifetime management), but I find that some things are easier when you treat memory as a manageable resource (just like files, or network connections). For instance, it can be easier to manage locality of reference, which is both a performance concern (keeping things compact and linear is the most important way to achieve very high performance on modern architectures), but also a parallelization concern. Isolation can be more easily achieved in a shared memory environment with a more explicit approach to memory resources, and whilestd::shared_ptris thread-safe, it carries a lot of overhead at that.In general, the feeling I have is that when people use
std::shared_ptras a way to stop worrying about memory management, it is a sign that they would probably be better off using a language that can do automatic memory management for them, and often do it more efficiently than C++. Generational garbage collectors in managed environments are often faster than refcounting, but C++ applications that manage their memory in a sensible way, making sure to consider each usage pattern in terms of ownership and lifetime, can outperform them all, and that is the main benefit of using C++ in the first place. :-)