gpt4 book ai didi

c++ - 通过 std::unique_ptr 扩展变量的生命周期

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:50 29 4
gpt4 key购买 nike

使用 C++11 unique_ptr,对象的生命周期似乎被延长到其通常范围之外,如下面(相当人为的)示例所示:

#include <iostream>
#include <memory>

using namespace std;

int main()
{
unique_ptr<char> uPtr(nullptr);
{
char c = 'X';
cout << "c = " << c << endl;
uPtr.reset(&c);
c = 'Y';
}
cout << "c = " << *uPtr << endl;

return 0;
}

输出:
c = X
c = Y

通常在作用域结束时释放的字符 c 一直存在到程序结束。第二个输出是“Y”,表明 unique_ptr 不只是简单地复制它的值。

是否建议以某种方式延长变量的生命周期?
这是否安全,或者它是否具有与引用相同的危险?

最佳答案

With the C++11 unique_ptr, an object's lifespan can be extended outside of its usual scope

不,它不能。

The character c, which would usually be released at the end of the scope, survives until the end of the program.

不,它没有,它一直存在到范围结束,就像正常情况一样。

The second output is 'Y', showing that the unique_ptr does not simply copy its value.

你是对的,unique_ptr 不会复制它指向的值。但是你在这里的输出是无关紧要的,因为当你取消引用那个指针时你的代码有未定义的行为,因为它指向的东西不再存在。当 unique_ptr 被销毁并在该位置调用 delete 时,代码再次具有未定义的行为(尽管您可以提供无操作删除器)。

Is it recommended to extend the lifespan of a variable in an way? Is it safe...

显然没有也没有。

or does it carry the same dangers as a reference?

是的,这类似于从函数返回对局部变量的引用。它甚至更类似于拥有一个悬空指针并取消引用它,此外还对该位置调用了 delete 以获得额外的未定义行为。

关于c++ - 通过 std::unique_ptr 扩展变量的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18221555/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com