c++ - 如果原始指针超出范围,智能指针是否保留分配的内存?

标签 c++ c++17 smart-pointers

我找不到类似的示例,但以下内容有效吗?

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/

相关文章:

c++ - 相机跟随播放器opengl

c++ - struct 中不可访问的模板化构造函数

c++ - "The World' s Dumbest Smart Pointer 有什么意义?”

c++ - std::launder 和严格的别名规则

c++ - 删除删除/删除[]

c++ - 共享指针存储在存储在共享指针中的另一个对象内的智能指针 vector 中(Shareption)

c++ - std::shared_ptr 复制构造函数线程安全

c++ - 具有大整数的 mod % 运算符的局限性

c++ - 捕获无效输入的最常见/最简单的方法

c++ - 如何在按下空格或制表符之前从标准输入读取输入?