choxsword
choxsword

Reputation: 3359

Why does shared_ptr needs to hold reference counting for weak_ptr?

Quoted from C++ Primer $12.1.6:

A weak_ptr (Table 12.5) is a smart pointer that does not control the lifetime of the object to which it points. Instead, a weak_ptr points to an object that is managed by a shared_ptr. Binding a weak_ptr to a shared_ptr does not change the reference count of that shared_ptr. Once the last shared_ptr pointing to the object goes away, the object itself will be deleted. That object will be deleted even if there are weak_ptrs pointing to it—hence the name weak_ptr, which captures the idea that a weak_ptr shares its object “weakly.”

However,I've read an article says:

using make_shared is more efficient. The shared_ptr implementation has to maintain housekeeping information in a control block shared by all shared_ptrs and weak_ptrs referring to a given object. In particular, that housekeeping information has to include not just one but two reference counts:

  1. A “strong reference” count to track the number of shared_ptrs currently keeping the object alive. The shared object is destroyed (and possibly deallocated) when the last strong reference goes away.

  2. A “weak reference” count to track the number of weak_ptrs currently observing the object. The shared housekeeping control block is destroyed and deallocated (and the shared object is deallocated if it was not already) when the last weak reference goes away.

As far as I know,the shared_ptr created by make_shared is in the same control block with those ref countings.So the object will not be released until the last weak_ptr expires.

Question:

  1. Is the Primer wrong? Because weak_ptr will actually affects the lifetime of that object.
  2. Why does the shared_ptr need to track its weak refs?The weak_ptr can tell if the object exists by checking the strong refs in control blocks,so I think the control block does not need to track the weak refs.
  3. Just for curiosity,what does the control block created by shared_ptr look like?Is it something like:

    template<typename T>
    class control_block
    {
       T object;
       size_t strong_refs;
       size_t weak_refs;
       void incre();
       void decre();
       //other member functions...
    };
    //And in shared_ptr:
    template<typename T>
    class shared_ptr
    {
       control_block<T> block;//Is it like this?So that the object and refs are in the same block?
       //member functions...
    };
    

Upvotes: 12

Views: 5091

Answers (4)

Poniros
Poniros

Reputation: 137

A nice first step would be making the difference between destruction and de-allocation clear in your mental representation of the concept — which would also be the preferable step over the is-an-implementation-detail-you-don't-need-to-care-about ( kindly alluded ), ignorance-reinforcing step.

So, let SeriousObject be a class, having size approximately half of your system's memory and taking control of the mouse upon construction, and us consider the implied being side-effects of a destructed, yet not de-allocated instance of the SeriousObject in this scenario. In such case, although the mouse control is back, you are still with only half of your memory available. Worst case scenario, somewhere in the code a forgotten, or even worse leaked, weak_ptr exists, leaving your memory with a lame, mood killer and show stopper 50% remainder for the rest of the execution. But hey, at least it's not leaked, right?

Assuming concluding duties here go my suppositions on each of your questions:

  1. Being not actually knowing, I would boldly bet, half my money on the authors having double-checked the text before publifying it, and the other half on the error itself being certainly discovered by now, should it existed in the first place.
  2. Because in that case, wherein the weak_ptr s are not being tracked, shared_ptr s and control block both having been destroyed, and at least one weak_ptr pointing to the object exists, what do you think will happen, the moment when a weak_ptr tries to, as you too so suggested, check the strong refs in the control block? ... Migrains all over the place.
  3. This time, being definitely not knowing, I will say just this: you, as well as I and many other coding-related guys, forget this humble resource, this uh..yea..there's also this—on one hand—definitely not useless to have—on the other—thing, which also happens to be a free, open-source, real-life-case, industry-level-quality knowledge resource. Proceed, brothers! The time has come, the time to seize, what to us, and what by blood and definition, have so always been and so forever shall inviolably be, our at birth delivered right, our through honor enslaving privilege, and our so as to and so beyond death bound duty!

PS ( or more like BTW, actually )

My personal baffling is not with the weak_ptr counting, but with the decision to make such an optimization during that specific stage of the object's lifetime, I'm referring to the in-one-go-allocation-type-optimization and elaborating, what I mean is choosing to optimize the shortest possible, single-time-occuring lifetime stage, while accepting paying such cost with such technical and behavioral side-effects and in exchange taking really up and absolutely effortlessly a handful of goat feces as the reaped fruits of their labors. Pff

Upvotes: 0

MateuszL
MateuszL

Reputation: 2983

Both weak_ptr and shared_ptr point to memory containing control block. If you delete control block as soon as shared_ptr counter reaches 0 (but weak counter doesn't), you are left with weak_ptrs pointing to garbage memory. Then when you try to use weak_ptr, it reads deallocated memory and bad things happen (UB).

For this reason, control block must be left alive (allocated and constructed, not destroyed nor deallocated) as long as any weak_ptr may try to read it.

Main (pointed-to) object will be destroyed and may (hopefully) be deallocated as soon as shared counter reaches 0. Control block will be destroyed and deallocated when both counters reach 0.

Upvotes: 3

BoBTFish
BoBTFish

Reputation: 19767

The reference count controls the lifetime of the pointed-to-object. The weak count does not, but does control (or participate in control of) the lifetime of the control block.

If the reference count goes to 0, the object is destroyed, but not necessarily deallocated. When the weak count goes to 0 (or when the reference count goes to 0, if there are no weak_ptrs when that happens), the control block is destroyed and deallocated, and the storage for the object is deallocated if it wasn't already.

The separation between destroying and deallocating the pointed-to-object is an implementation detail you don't need to care about, but it is caused by using make_shared.

If you do

shared_ptr<int> myPtr(new int{10});

you allocate the storage for the int, then pass that into the shared_ptr constructor, which allocates storage for the control block separately. In this case, the storage for the int can be deallocated as early as possible: as soon as the reference count hits 0, even if there is still a weak count.

If you do

auto myPtr = make_shared<int>(10);

then make_shared might perform an optimisation where it allocates the storage for the int and the control block in one go. This means that the storage for the int can't be deallocated until the storage for the control block can also be deallocated. The lifetime of the int ends when the reference count hits 0, but the storage for it is not deallocated until the weak count hits 0.

Is that clear now?

Upvotes: 25

madlers
madlers

Reputation: 111

The weak_ptr need to point to something that can tell if the object exist or not so it knows if it can be converted to a shared_ptr. Therefore a small object is needed to housekeep this information.

This housekeeping control block needs to be destroyed when the last week_ptr (or shared_ptr) is removed. Therefore it has to keep count of both the shared_ptr and the week_ptr's.

Note that the housekeeping control block is not the same as the object the ptr's point to and therefore the week_ptr do not affect the objects lifetime.

There is a bunch of different ways to implement smart pointers depending on what behavior you would like it to have. If you want to know more I would recommend "Modern C++ Design" by Alexandrescu (https://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315)

Upvotes: 10

Related Questions