Remix.run Logo
fluoridation 5 days ago

Huh? What do you mean? The point of std::weak_ptr is that it's non-owning, so it has no effect on the lifetime of the pointed object.

deschutes 5 days ago | parent | next [-]

You are correct, it does not affect the lifetime of the pointed object (pointee).

But a shared_ptr manages at least 3 things: control block lifetime, pointee lifetime, and the lifetime of the underlying storage. The weak pointer shares ownership of the control block but not the pointee. As I understand this is because the weak_ptr needs to modify the control block to try and lock the pointer and to do so it must ensure the control block's lifetime has not ended. (It manages the control blocks lifetime by maintaining a weak count in the control block but that is not really why it shares ownership.)

As a bonus trivia, make_shared uses a single allocation for both the control block and the owned object's storage. In this case weak pointers share ownership of the allocation for the pointee in addition to the control block itself. This is viewed as an optimization except in the case where weak pointers may significantly outlive the pointee and you think the "leaked" memory is significant.

AlotOfReading 5 days ago | parent | prev [-]

It has no effect on the lifetime of the object, but it can affect the lifetime of the allocation. The reason is that weak_ptr needs the control block, which make_shared bundles into the same allocation as the object for optimization reasons.

Quoting cppreference [0]:

    If any std::weak_ptr references the control block created by std::make_shared after the lifetime of all shared owners ended, the memory occupied by T persists until all weak owners get destroyed as well, which may be undesirable if sizeof(T) is large.
[0] https://en.cppreference.com/w/cpp/memory/shared_ptr/make_sha...