将所有权从std :: shared_ptr移动到std :: unique_ptr [英] Move ownership from std::shared_ptr to std::unique_ptr

查看:277
本文介绍了将所有权从std :: shared_ptr移动到std :: unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 A ,其类型为 std :: unique_ptr

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

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

在代码中,我使用少量 std :: shared_ptr s指向同一个对象。现在我想实现的是将所有权移动到我的类中的 std :: unique_ptr ,所以如果所有 shared_ptr s将被销毁,我的对象将保持活着,只要这个 unique_ptr 将保持活着。

And somewhere in code, I'm using few std::shared_ptrs which point to the same object. Now what I'd like to achieve is to move ownership to this std::unique_ptr in my class, so that if all shared_ptrs will be destroyed, my object will stay alive as long as this unique_ptr will stay alive.

我的问题是 - 是否可以将所有权从 std :: shared_ptr 移动到

My question is - is it possible to move ownership from std::shared_ptr to std::unique_ptr and if yes, how can I do this?

推荐答案

在逻辑上,这样的情况是这样的:std :: unique_ptr 对我来说没有意义。

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

假设有一段时间可以转移所有权,但您只能在 shared_ptr alives;如果是这样,那么您仍然可以使用 shared_ptr 作为 A 假装 unique_ptr

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.

然后您评论:


这是真的,我可以在A类中创建 shared_ptr 。我认为我误解了一个概念。我想以这种方式表现:如果 unique_ptr 死了,对象本身也会死,即使 shared_ptr 指向它,但是这是愚蠢的,因为他们不知道对象本身被销毁,因此他们不会 nullptr s。

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.

在这种情况下,你正在查看错误的智能指针。您可能需要的是 std :: weak_ptr 。如果是,请确保您使用一个 std :: shared_ptr ,所有其他为 std :: weak_ptr

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.

这篇关于将所有权从std :: shared_ptr移动到std :: unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆