为什么std :: unique_ptr向量获得无效的指针异常 [英] why std::unique_ptr vector gets invalid pointer exception

查看:125
本文介绍了为什么std :: unique_ptr向量获得无效的指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了简单的代码来帮助我理解智能指针:

I wrote simple code to help me understand smart pointers:

string s = "str";
vector <unique_ptr<string>> pv ;

pv.push_back(unique_ptr<string>(&s));
cout<<*(pv[0])<<endl;

此代码可以很好地编译,但是会导致运行时错误:

This code compiles fine, but gets me a runtime error:


str
*'...'中的错误:munmap_chunk():无效的指针:0x00007ffd956e57e0 * 中止(内核已转储)

发生了什么事,我做错了什么?

What happened and what have I done wrong?

推荐答案

std :: unique_ptr 的析构函数中,它将调用& s 指针上的删除,该指针不是通过 new

In the std::unique_ptr's destructor it will call delete on the &s pointer which was not allocated via new.

只需使用:

std::vector<std::string> vector;
vector.emplace_back("str");
std::cout << pv[0] << std::endl;

不需要 std :: unique_ptr< std :: string> 那里。

这篇关于为什么std :: unique_ptr向量获得无效的指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆