Std::shared_ptr's secret constructor
justsoftwaresolutions.co.uk
justsoftwaresolutions.co.uk
std::shared_ptr is already something that should only be used sparingly. Not because refcounting adds a tiny bit of overhead, but because it can easily lead to confusion about who owns what. If you use the aliasing constructor, it's even more confusing.
The C++ committee has been trying to get ownership semantics to work right for about 20 years now. Remember auto_ptr? They've piled hacks on top of of hacks, and it almost works. Almost.
The Rust borrow checker is the right way to do this. Rust has a clear conceptual model of ownership and a way to enforce it. Trying to emulate that via the type system and templates is like pounding a screw. It sort of works, until it doesn't.
Rust doesn't have all the answers, but the ownership model and borrow checking are a huge advance. Any new attempt to solve this problem has to be at least as good.
Or functional "persistent" datastructures.
I think you may occasionally find the overhead is more than tiny. Especially when you consider that shared_ptr should also be doing atomics to keep things thread safe.
Anyway, I've heard similar recommendations against overuse of shared_ptr for various reasons and I understand them. But I think it's interesting that one community's recommendations can completely contradict another's. This is before taking into consideration the diverse opinions on what the "proper" C++ is. Compare the C++ world to say, the objc world, where in the latter, everything is refcounted by default, and ARC gives you the equivalent of shared_ptr everywhere all the time. They don't seem to mind.
Way I think of it is that using shared_ptr gets me some of the productivity advantages of garbage collected languages, with some of the costs. In areas where performance is not terribly sensitive, this can be a good trade off.
On the other hand, you're absolutely right that this constructor is too clever by half.
Obviously, you would only want to use this feature when you have a reason to want to use it.
std::shared_ptr has no problems with confusion about who owns what, unless you start making cycles. Ownership is shared.
That said, this constructor is not a secret. It's obscure yet occasionally useful, like half of C++.
I never use it until now but I can see some possible use for it.