问题
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