为什么不能从unique_ptr构造weak_ptr? [英] Why can't a weak_ptr be constructed from a unique_ptr?

查看:321
本文介绍了为什么不能从unique_ptr构造weak_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确,那么weak_ptr不会增加托管对象的引用计数,因此它不表示所有权.它只是让您访问一个对象的生命周期,该对象的生命周期由其他人管理. 所以我真的不明白为什么不能从unique_ptr构造weak_ptr,而只能从shared_ptr构造.

If I understand correctly, a weak_ptr doesn't increment the reference count of the managed object, therefore it doesn't represent ownership. It simply lets you access an object, the lifetime of which is managed by someone else. So I don't really see why a weak_ptr can't be constructed from a unique_ptr, but only a shared_ptr.

有人可以简要解释一下吗?

Can someone briefly explain this?

推荐答案

std::weak_ptr不能使用,除非您通过lock()方式将其转换为std::shared_ptr.如果标准允许您的建议,则意味着您需要将std :: weak_ptr转换为唯一才能使用它,这违反了唯一性(或重新发明了std::shared_ptr)

std::weak_ptr can't be used unless you convert it to std::shared_ptr by the means of lock(). if the standard allowed what you suggest, that means that you need to convert std::weak_ptr to unique in order to use it, violating the uniqueness (or re-inventing std::shared_ptr)

为了说明,请看两段代码:

In order to illustrate, look at the two pieces of code:

std::shared_ptr<int> shared = std::make_shared<int>(10);
std::weak_ptr<int> weak(shared);

{
*(weak.lock()) = 20; //OK, the temporary shared_ptr will be destroyed but the pointee-integer still has shared  to keep it alive
}

现在有您的建议:

std::unique_ptr<int> unique = std::make_unique<int>(10);
std::weak_ptr<int> weak(unique);

{
*(weak.lock()) = 20; //not OK. the temporary unique_ptr will be destroyed but unique still points at it! 
}

话虽如此,您可能会建议只有一个unique_ptr,并且仍然可以取消引用weak_ptr(而无需创建另一个unique_ptr),那么就没有问题.但是unique_ptrshared_ptr有一个引用之间有什么区别?或此外,使用get获取的常规unique_ptr和C指针之间有什么区别?

That has been said, you may suggest that there is only one unique_ptr, and you still can dereference weak_ptr (without creating another unique_ptr) then there is no problem. But then what is the difference between unique_ptr and shared_ptr with one reference? or moreover, what is the difference between a regular unique_ptr and C-pointers an get by using get?

weak_ptr不适用于一般的非拥有资源",它有一个非常特定的工作-weak_ptr的主要目标是防止shared_ptr的循环指向,这会导致内存泄漏.其他任何操作都需要使用普通的unique_ptrshared_ptr.

weak_ptr is not for "general nonowning resources", it has a very specific job - The main goal of weak_ptr is to prevent circular pointing of shared_ptr which will make a memory leak. Anything else needs to be done with plain unique_ptr and shared_ptr.

这篇关于为什么不能从unique_ptr构造weak_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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