Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why weak pointer is getting created with shared_ptr?

I have written following simple code,

#include <iostream>
#include <memory>

struct Foo
{
    Foo()      { std::cout << "Foo::Foo\n";  }
    ~Foo()     { std::cout << "Foo::~Foo\n"; }
    void bar() { std::cout << "Foo::bar\n";  }
};

int main()
{
    std::shared_ptr<Foo> p1(new Foo);//this line

    p1->bar();

    std::shared_ptr<Foo> p2(p1);
}

And in watch window I got,

p2  std::__1::shared_ptr<Foo>   ptr = 0x100104350 strong=2 weak=1   
p1  std::__1::shared_ptr<Foo>   ptr = 0x100104350 strong=2 weak=1   

Now, I can understand strong=2, but why weak = 1?

Secondly, in code I changed code to,

std::shared_ptr<Foo> p1(std::move(new Foo));

Because, may be one weak pointer is because of nameless object. So I have moved it while creating p1, still I get same output in watch window.

Please suggest which point I am missing?

like image 667
Pranit Kothari Avatar asked Feb 12 '23 03:02

Pranit Kothari


1 Answers

The value shown for weak is not the number of weak_ptr objects that exist, it is the "weak count".

The typical shared_ptr implementation (originating in Boost) stores two counts in the control block, a strong count, S, which is the number of active shared_ptr objects and a weak count, W, which is the number of active weak_ptr objects + (S != 0)

So if there are any shared_ptr objects then W will always be non-zero.

The reason for this is that the implementation destroys the owned object when S == 0 and destroys the control block when W == 0

Since you don't want to destroy the control block while there are shared_ptr objects using it, W must not reach 0 while there are active shared_ptr objects.

like image 52
Jonathan Wakely Avatar answered Feb 14 '23 16:02

Jonathan Wakely