Why is a weak pointer created using shared_ptr?

I wrote the 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 the 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 the code, I changed the code to,

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

Because maybe one weak pointer is due to an unnamed object. So I moved it when creating p1, but I still get the same result in the viewport.

Please indicate which moment I am missing?

+4
source share
1 answer

The value shown for weakis not the number of objects weak_ptrthat exist, it is a "weak account".

shared_ptr ( Boost) , , S, shared_ptr , W, - weak_ptr + (S != 0)

, - shared_ptr, W .

, S == 0 , W == 0

, shared_ptr , , W 0, shared_ptr.

+7

All Articles