Move ownership from std::shared_ptr to std::unique_ptr

前端 未结 1 2032
-上瘾入骨i
-上瘾入骨i 2021-01-04 02:17

I have a class A which has a field of type std::unique_ptr:

class A
{
public:
   std::unique_ptr pointer;
// class body
};
<         


        
1条回答
  •  隐瞒了意图╮
    2021-01-04 02:49

    Logically such a scenario doesn't make sense to me.

    Suppose for a while that it is possible to transfer the ownership, but you could do that only when you're sure that there is only one shared_ptr alives; if that is the case, then you can still use shared_ptr as member of A and pretend that it is unique_ptr.

    And then you commented:

    That's true, I could create shared_ptr in A class. I think I misunderstood a concept a bit again. I wanted to behave it in this way: if unique_ptr dies, the object itself dies too, even though shared_ptrs still point to it, but that's silly as they wouldn't know that object itself was destroyed and therefore they wouldn't be nullptrs.

    In that case, you're looking at the wrong smart pointer. What you probably need is called std::weak_ptr. If so, then make sure you use one std::shared_ptr and all others as std::weak_ptr.

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