gpt4 book ai didi

c++ - 在对象被销毁后释放一个 unique_ptr

转载 作者:行者123 更新时间:2023-11-30 03:42:46 27 4
gpt4 key购买 nike

下面的代码合法吗?我担心的是在 Start 方法中销毁对象后使用 .release 方法。

class Foo
{
public:
Foo()
{
std::cout << "Foo ctor\n";
}

~Foo()
{
std::cout << "Foo dtor\n";
}

void Start()
{
std::unique_ptr<Foo> ptr(this);
}
};

int main(int argc, char* argv[])
{
auto ptr = std::make_unique<Foo>();
ptr->Start();
ptr.release();
}

我在 vs12 中试过了,它没有提示。

最佳答案

std::unique_ptr 是指针的容器,其上只有一个操作:当它被销毁时删除它引用的实例。 (或调用 reset() 时)

因此,只要不调用析构函数或重置函数,您就会拥有正在运行的代码。但是,如果您重写 Start() 函数以同时抛出异常,则会发生崩溃。 (没有额外的捕获代码)另一个风险是您在程序中保留了悬空指针,您必须小心。

是的,你的代码是合法有效的,但我不推荐它,因为它容易出错。我宁愿推荐写这样的东西:

static void Start(std::unique_ptr<Foo> &&owner)
{
std::unique_ptr<Foo> ptr(std::move(owner));
}

或者如果您真的需要此方法中的所有权(让我们考虑线程),将其设为 std::shared_ptr 并共享所有权:

class Foo : std::enable_shared_from_this<Foo>
{
void Start()
{
std::shared_ptr<Foo> ptr = shared_from_this();
}
}

关于c++ - 在对象被销毁后释放一个 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659162/

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