Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Trouble understanding very basic concept of using smart pointer

I'm getting back into c++ and can't understand why this is giving me an error:

#include <memory>

int main(int argc, char** argv)
{
    std::string str = "hello";
    std::shared_ptr<std::string> pStr(&str);

    return 0;
}

Just running this gives me an error: Expression: BLOCK_TYPE_... Why?

like image 913
hacksoi Avatar asked Dec 06 '25 02:12

hacksoi


2 Answers

The smart pointer is supposed to manage the lifetime of the object pointed at by the pointer it holds. But in this case, you passed it a pointer to an object that manages itself. At the end of the scope, the smart pointer's destructor tries to delete an object that "deletes" itself.

like image 191
juanchopanza Avatar answered Dec 10 '25 08:12

juanchopanza


The line

std::string str = "hello";

creates a local variable on the stack. The destructor for this variable is called automatically when it goes out of scope at the end of the block. You should not try to delete objects on the stack. This is what your smart pointer will try to do when it goes out of scope.

If you create the string on the heap, i.e.

std::string* str = new std::string("hello");
std::shared_ptr<std::string> pStr(str);

then the smart pointer will correctly do the clean up when it goes out of scope.

like image 42
opetroch Avatar answered Dec 10 '25 08:12

opetroch