【发布时间】:2018-08-01 15:34:01
【问题描述】:
我有一个像这样的简单 C++ 程序:
#include <iostream>
#include <list>
#include <memory>
int main(void) {
std::list<std::unique_ptr<int>> l;
int x = 5;
// throws runtime error: pointer being freed was not allocated
l.emplace_back(&x);
}
当程序运行时,我得到以下输出:
a.out(59842,0x7fffb13d1380) malloc: *** error for object 0x7ffee81489ac: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
[1] 59842 abort ./a.out
这告诉我,在销毁列表期间,已创建的 unique_ptr 对象被销毁,而在销毁期间,指向 x 的指针被释放,而它从未被 malloced 释放。
但是我希望在unique_ptr 超出范围并且是destroyed 的情况下也会发生同样的情况:
#include <iostream>
#include <list>
#include <memory>
int main(void) {
int x = 5;
// does not throw runtime error when falling out of scope and being destructed
std::unique_ptr<int> p(&x);
}
但是,当上面的unique_ptr p 超出范围并被销毁时,程序运行良好。为什么第一个程序在销毁unique_ptr 时给我一个错误,而第二个程序却没有?为什么在列表中放置 unique_ptr 会导致其破坏失败?
【问题讨论】:
-
两者都是 UB,因此行为可能不同。
标签: c++ c++11 unique-ptr