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