我找不到类似的示例,但以下内容有效吗?
std::unique_ptr<int> x;
if (true) { // assume some condition here which evaluates to true
int * y = new int(5); // assume a function call here which returns a pointer
x.reset(y);
}
// is x still holding the memory allocated?
// Does it matter that y is out of scope here?
cout << *x << endl; // 5
最佳答案
用new
分配的任何东西都有一个生命周期,直到它被传递给delete
,或者程序结束(当然)。
变量y
的生命周期以 block 结束,但不是它指向的数据。
所以是的,这是完全有效的。
关于c++ - 如果原始指针超出范围,智能指针是否保留分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75961798/