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

0 c++ smart-pointers

有人可以告诉我这里发生了什么吗?

int* stackint = new int(5);

{
    std::unique_ptr<int> myInt(stackint);    
    *myInt = 8;

}

std::cout << *stackint; // 0
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*ner 5

这是一个注释:

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
Run Code Online (Sandbox Code Playgroud)