Search code examples
c++pointersshared-ptr

C++ shared_ptr and built-in pointer


Delete twice built-in pointers cause undefined, but what happened in this situation? In this code, is shared pointer undefined?

string *str_1 = new string;
std::shared_ptr<string> str_ptr(str_1);

*str_1 = "C++";
cout << *str_ptr << endl;
*str_ptr = "C#";
cout << *str_1 << endl;

// str_1 & str_ptr refers same piece of memory    
delete str_1;

cout << *str_ptr << endl;  // Is this undefined?

Solution

  • Your code is undefined because after the call to deletion of the raw pointer, the shared_ptr is left with a dangling pointer reference. You then proceed to dereference the already freed memory (undefined behavior 1). When the shared_ptr goes out of scope, it will call delete on the pointer it was told to manage, which is freeing already freed memory (undefined behavior 2).

    As a convenience, shared_ptr allows initialization from a raw pointer, but you are supposed to allow it to manage the allocated memory afterwards. It is an error to manage the raw pointer (eg, delete it or initialize another shared_ptr) when you have given it to shared_ptr.

    It is actually better practice, when using shared_ptr to use the helper function make_shared.

    std::shared_ptr<std::string> sp = std::make_shared<std::string>("C++");
    

    This format avoids you having to deal with creating a raw pointer. It also turns out to be more efficient because it avoids an extra allocation the smart pointer would have to do if it was passed a raw pointer.