My question is: is there a case that share_ptr ref count is 0, while weak_ptr ref count is not 0?
Difference in make_shared and normal shared_ptr in C++
Referr this thread, showing that if a shared_ptr is created by make_shared
and there's weak_ptr, its control block will be alive until
both shared_ptr and weak_ptr's ref count gets 0. It says:
There must be a way for weak_ptrs to determine if the managed object is still valid (eg. for lock). They do this by checking the number of shared_ptrs that own the managed object, which is stored in the control block. The result is that the control blocks are alive until the shared_ptr count and the weak_ptr count both hit 0.
I had a quick test. I hope the shared_ptr
created by make_shared
, if there's weak_ptr pointing to it, its control block
will still hold sth after shared_ptr is destructed.
#include<memory>
#include<iostream>
using namespace std;
struct My {
int m_i;
My(int i) : m_i(i) { cout << "My ctor:" << m_i << '\n';}
~My() { cout << "My ctor:" << m_i << '\n';}
};
weak_ptr<My> wp1, wp2;
int main() {
{
auto sp1 = shared_ptr<My>(new My(30));
wp1 = weak_ptr<My>(sp1);
}
cout<< wp1.use_count() << endl;
{
auto sp2 = make_shared<My>(40);
wp2 = weak_ptr<My>(sp2);
}
cout<< wp2.use_count() << endl;
return 0;
}
Both use_count
will print 0
, my program didn't seems to show whether the control blocks
is alive or not.
So, how can we prove that The result is that the control blocks are alive until both shared_ptr and weak_ptr's ref count gets 0
?
Any sample code that could test/prove this theory?