Question

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

Was it helpful?

Solution

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 */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top