Assigning shared_ptr to weak_ptr

杀马特。学长 韩版系。学妹 提交于 2019-12-20 06:14:05

问题


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.



来源:https://stackoverflow.com/questions/55214440/assigning-shared-ptr-to-weak-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!