我编写了简单的代码来帮助我理解智能指针:
string s = "str";
vector <unique_ptr<string>> pv ;
pv.push_back(unique_ptr<string>(&s));
cout<<*(pv[0])<<endl;
这段代码编译得很好,但给我一个运行时错误:
str
*“...”中的错误:munmap_chunk():无效指针:0x00007ffd956e57e0 *中止(核心转储)
发生了什么以及我做错了什么?
In the std::unique_ptr
它将调用的析构函数delete
on the &s
未通过分配的指针new
.
只需使用:
std::vector<std::string> vector;
vector.emplace_back("str");
std::cout << pv[0] << std::endl;
没有必要std::unique_ptr<std::string>
there.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)