简体   繁体   中英

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?

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.

sharped_ptr is no magic. It simply calls delete once the last shared_ptr to an object is destroyed. Thus, your code calls delete twice, once when you delete str_1 and then when str_ptr goes out of scope. Thus, using a shared_ptr doesn't change anything in comparision to calling delete twice explicitly: The result is undefined behaviour.

shared_ptr was invented to take the burden of explicit delete calls from you. Thus, there is also simply no reason for using shared_ptr and explicit delete together. So even if it did not result in undefined behaviour, my advice would still be: Don't do it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM