There are two ways to do this:
- Create a new copy on the heap and make shared_ptr out of it.
- Make it shared_ptr with zero delete.
The first can be done by writing
auto newPtr = std::make_shared<Foo>( foo );
This works if the Foo class is Foo . Second can be done
auto newPtr = std::shared_ptr<Foot>( &foo, [](void*){} );
You are not creating a new copy of the object here. However, it is safe if you can guarantee that the pointer is not accessible after Foo goes out of scope. Otherwise, you will gain access to the destroyed object, and the program will most likely do random material.
source share