Assigning shared_ptr to weak_ptr

2020-05-08 08:48发布

问题:

I want to assign constructed shared_ptr to weak_ptr:

std::weak_ptr<void> rw  = std::shared_ptr<void>(operator new(60), [](void *pi) { operator delete(pi); });

But, when I do rw.expired(), it shows expired means it is empty. Any suggestions where I am going wrong?

Thanks in advance.

回答1:

Purpose of std::shared_ptr is to release managed object when last shared pointer which points to it is destroyed or reassigned to somewhere else. You created a temporary shared ptr, assgned it to std::weak_ptr and then it is just destroyed at the end of the expression. You need to keep it alive:

auto shared = std::shared_ptr<void>(operator new(60), [](void *pi) { operator delete(pi); });
std::weak_ptr<void> rw  = shared;

now rw would not expire at least while shared is still alive.