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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With