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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With