【问题标题】:why std::unique_ptr vector gets invalid pointer exception为什么 std::unique_ptr 向量得到无效指针异常
【发布时间】:2015-11-28 05:01:02
【问题描述】:

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

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

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

这段代码编译得很好,但给我一个运行时错误:

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

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

【问题讨论】:

  • 一个unique_ptr 到堆栈上的东西没有意义。

标签: c++11 vector runtime-error smart-pointers unique-ptr


【解决方案1】:

std::unique_ptr 的析构函数中,它将在&amp;s 指针上调用delete,该指针不是通过new 分配的。

只需使用:

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

那里不需要std::unique_ptr&lt;std::string&gt;

【讨论】:

    【解决方案2】:

    您的字符串被破坏了两次 - 一次是您的 pv 超出范围并被删除,释放其所有包含的 unique_ptr 元素,一次是 s 超出范围。

    要使用唯一指针的向量(或一般使用唯一指针),它们必须没有别名。所以你可以写:

    auto *s = new std::string("str");
    pv.push_back(std::unique_ptr<std::string>(s));
    // do not write "delete s" anywhere...
    

    或者,更简单、更安全:

    pv.push_back(std::make_unique<std::string>("str")); // make_unique is C++14
    

    甚至:

    std::unique_ptr<std::string> p{new std::string("str")};
    pv.push_back(std::move(p));
    // Do not attempt to use p beyond this point.
    

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 1970-01-01
      • 2011-12-13
      • 2011-04-14
      • 2012-07-23
      • 2019-01-22
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多