从堆栈分配的原始指针构造智能指针

Constructing smart pointer from stack allocated raw pointer

本文关键字:指针 智能 原始 堆栈 分配      更新时间:2023-10-16

有人可以启发我这里发生的事情吗?

int* stackint = new int(5);
{
std::unique_ptr<int> myInt(stackint);    
*myInt = 8;
}
std::cout << *stackint; // 0

这里到底发生了什么?我理解智能指针,当你用新的或make_unique构造它们时,当你将堆栈指针传递给它们的构造函数时会发生什么?

下面是一个注释:

int* stackint = new int(5);   // an int is allocated on the heap, and set to 5
{
std::unique_ptr<int> myInt(stackint);  // myInt takes ownership of the allocation
*myInt = 8;  // The value 5 is overwritten by 8
}  // myInt goes out of scope, its destructor deletes the heap allocation        
std::cout << *stackint; // undefined behavior:  attempt to read from already-freed memory

代码具有未定义的行为。

std::unique_ptr<int> myInt(stackint);构造一个拥有stackint指向的对象unique_ptr。指针本身具有的存储类型无关紧要,只有其值传递给构造函数,并且该指向通过调用new创建的int对象,这意味着该int对象具有动态存储持续时间

然后myInt的析构函数在块的末尾被调用(}(,并delete它管理并且stackint仍然指向的int对象,这意味着stackint的值现在是一个无效的指针值

然后,使用*stackint取消引用该无效指针值,这会导致未定义的行为。