Assigning shared_ptr to weak_ptr

前端 未结 1 1150
忘掉有多难
忘掉有多难 2021-01-25 06:21

I want to assign constructed shared_ptr to weak_ptr:

std::weak_ptr rw  = std::shared_ptr(operator new(60), [](void *pi) { operator delet         


        
1条回答
  •  轮回少年
    2021-01-25 06:35

    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(operator new(60), [](void *pi) { operator delete(pi); });
    std::weak_ptr rw  = shared;
    

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

    0 讨论(0)
提交回复
热议问题