std::shared_ptr initialized with other shared_ptr data

浪子不回头ぞ 提交于 2021-02-11 18:15:54

问题


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 */
}

Am I doing it wrong? Or do you think is better to modify directly the data in my_reference, without doing this redundant operation?

Regards

Mike


回答1:


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.

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).

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 */
}


来源:https://stackoverflow.com/questions/21876003/stdshared-ptr-initialized-with-other-shared-ptr-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!