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

问题描述 投票:0回答:1

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

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
c++ c++17 smart-pointers
1个回答
2
投票

你用

new
分配的任何东西都有一个生命周期,直到它被传递给
delete
,或者程序结束(当然)。

变量的生命周期

y
以块结束,但不是它指向的数据。

所以是的,这是完全正确的。

© www.soinside.com 2019 - 2024. All rights reserved.