我找不到类似的例子,但以下有效吗?
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
以块结束,但不是它指向的数据。
所以是的,这是完全正确的。