Update a smart pointer using a reference

人盡茶涼 提交于 2019-12-13 08:45:47

问题


I would like to update a smart pointer from a reference.

shared_ptr<My_Toy> my_toy_ptr;

// Something...

void update(shared_ptr<My_Toy> my_toy_ptr, My_Toy& toy){

     my_toy_ptr = &toy;
}

...but his code generates an error.

How can I do this operation?


回答1:


Don't pass the address of a stack allocated object to a std::shared_ptr. toy will be destructed at the end of its scope and the std::shared_ptr will attempt to delete something that was not newd. The address held by a std::shared_ptr must be that of a dynamically allocated object (although a custom deleter can be provided, but that is not the case here).

To change the object that a std::shared_ptr is managing use std::shared_ptr::reset().



来源:https://stackoverflow.com/questions/18314544/update-a-smart-pointer-using-a-reference

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