std::shared_ptr 用其他 shared_ptr 数据初始化 [英] std::shared_ptr initialized with other shared_ptr data
问题描述
我最近在使用新的 C++11 特性,例如 std::shared_ptr,因为我将 C 代码转换为类,并且在这段代码中大量使用了老式"指针.我有一个疑问:在一个类的方法中,我使用本地 shared_ptr,我可以用传递给另一个 smart_ptr 的引用的数据初始化它们,然后修改数据吗?示例:
I'm using recently new C++11 features such as std::shared_ptr, because I am converting a C code into Classes and in this code there is an heavy usage of "old-fashioned" pointers. I have one doubt: in a method of a class, where i use local shared_ptr, can i initialized them with the data of the passed reference to another smart_ptr and then modify the data? Example:
void myFunction(std::shared_ptr<T> &my_reference)
{
std::shared_ptr<T> my_local_ptr(my_reference.get());
/* Doing stuff on local pointer,
which modifies the object kept by my_reference pointer */
}
我做错了吗?还是你觉得直接修改my_reference里面的数据比较好,不做这个多余的操作?
Am I doing it wrong? Or do you think is better to modify directly the data in my_reference, without doing this redundant operation?
问候
迈克
推荐答案
您所做的是错误的(它是技术上有效的代码,但可能不是您想要的).当这样构造时,my_local_ptr
将指向与 my_reference
相同的对象,但它有自己的引用计数(初始化为 1).在标准术语中,它不会与 my_reference
共享所有权".
What you're doing is wrong (it's technically valid code, but probably not what you intended). When constructed like this, my_local_ptr
will point to the same object as my_reference
, but it will have its own reference count (initialised to 1). In standard terms, it will not "share ownership" with my_reference
.
并且一旦 my_local_ptr
超出范围,它会很高兴地调用删除器 - 销毁指向的对象,并使 my_reference
悬空.然后,当与 my_reference
共享所有权的最后一个 shared_ptr
被销毁时,它将调用其删除器,从而导致双重删除(除非悬空在此之前导致崩溃).
And once my_local_ptr
goes out of scope, it will happily call the deleter - destroy the object pointed to, and making my_reference
dangling. Then, when the last shared_ptr
sharing ownership with my_reference
gets destroyed, it will call its deleter, resulting in a double delete (unless the danglingness causes a crash before that).
如果你需要本地拷贝的 shared_ptr
传入(到底是为了什么?),一定要拷贝整个 shared_ptr
(包括所有权):
If you need a local copy, of the shared_ptr
passed in (what for, anyway?), definitely copy the whole shared_ptr
(including ownership):
void myFunction(std::shared_ptr<T> &my_reference)
{
std::shared_ptr<T> my_local_ptr(my_reference);
/* Doing stuff on local pointer,
which modifies the object kept by my_reference pointer */
}
这篇关于std::shared_ptr 用其他 shared_ptr 数据初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!