On Thursday, 11 February 2016 at 01:45:32 UTC, Matt Elkins wrote:
True, but with unique_ptr the max count is enforced by the compiler and can only be subverted by a programmer explicitly choosing to do so -- if that is possible with normal reference counting, I don't know of a way.

You "subvert" both unique_ptr and shared_ptr by taking the reference of the object and using it directly... Like a borrowed reference in Rust, except it is unchecked (by the compiler).


Moreover, there is no heap allocation required which may or may not matter for a given use case. Of course there are ways to avoid or mitigate heap allocations for reference-counted pointers, but the point is that unique_ptr has the next best thing to no overhead at all, which allows it to be used in a broader range of contexts.

Yes, I agree, I don't think reference counting is all that important. Although I tend to favour embedding objects rather than using unique_ptr... C++ supports it, but in a rather clunky way. I'd like to see a language that does that really well (sensible initialization tracking of embedded or global objects, so that you can safely delay initialization without resorting to using pointers).

I never really use shared_ptr, but it is quite rich. AFAIK you can swap one pointer for another, you can swap the underlying object without touching the pointers, you can use weak_ptr which checks the presence of the object.

I think shared_ptr is a good thing to have available, but you generally don't have to resort to using it. With a properly structured program you can get a long way with just unique_ptr and your own tailored made structs.

Reply via email to