c ++无法理解使用智能指针的非常基本的概念
c++ Trouble understanding very basic concept of using smart pointer
我正在回到 C++ 中,不明白为什么这会给我一个错误:
#include <memory>
int main(int argc, char** argv)
{
std::string str = "hello";
std::shared_ptr<std::string> pStr(&str);
return 0;
}
只是 运行 这给了我一个错误:表达式:BLOCK_TYPE_...
为什么?
智能指针应该管理它持有的指针指向的对象的生命周期。但在本例中,您向它传递了一个指向管理自身的对象的指针。在作用域的末尾,智能指针的析构函数试图删除一个 "deletes" 本身的对象。
行
std::string str = "hello";
在堆栈上创建一个局部变量。当该变量在块末尾超出范围时,将自动调用该变量的析构函数。您不应该尝试删除堆栈上的对象。这是您的智能指针在超出范围时将尝试执行的操作。
如果在堆上创建字符串,即
std::string* str = new std::string("hello");
std::shared_ptr<std::string> pStr(str);
然后智能指针将在超出范围时正确地进行清理。
我正在回到 C++ 中,不明白为什么这会给我一个错误:
#include <memory>
int main(int argc, char** argv)
{
std::string str = "hello";
std::shared_ptr<std::string> pStr(&str);
return 0;
}
只是 运行 这给了我一个错误:表达式:BLOCK_TYPE_... 为什么?
智能指针应该管理它持有的指针指向的对象的生命周期。但在本例中,您向它传递了一个指向管理自身的对象的指针。在作用域的末尾,智能指针的析构函数试图删除一个 "deletes" 本身的对象。
行
std::string str = "hello";
在堆栈上创建一个局部变量。当该变量在块末尾超出范围时,将自动调用该变量的析构函数。您不应该尝试删除堆栈上的对象。这是您的智能指针在超出范围时将尝试执行的操作。
如果在堆上创建字符串,即
std::string* str = new std::string("hello");
std::shared_ptr<std::string> pStr(str);
然后智能指针将在超出范围时正确地进行清理。