gpt4 book ai didi

c++ - unique_ptr boost 等效?

转载 作者:IT老高 更新时间:2023-10-28 13:58:16 27 4
gpt4 key购买 nike

在 boost 库中是否有 C++1x 的 std::unique_ptr 的等效类?我正在寻找的行为是能够拥有一个异常安全的工厂函数,就像这样......

std::unique_ptr<Base> create_base()
{
return std::unique_ptr<Base>(new Derived);
}

void some_other_function()
{
std::unique_ptr<Base> b = create_base();

// Do some stuff with b that may or may not throw an exception...

// Now b is destructed automagically.
}

编辑:现在,我正在使用这个 hack,这似乎是目前我能得到的最好的......

Base* create_base()
{
return new Derived;
}

void some_other_function()
{
boost::scoped_ptr<Base> b = create_base();

// Do some stuff with b that may or may not throw an exception...

// Now b is deleted automagically.
}

最佳答案

如果没有 C++0x(它是标准库的一部分,因此 Boost 不需要提供它),就不可能创建像 unique_ptr 这样的东西。

特别是没有右值引用,这是 C++0x 中的一个特性,unique_ptr 的健壮实现是不可能的,不管有没有 Boost。

在 C++03 中,有一些可能的替代方案,尽管每个都有其缺陷。

  • boost::shared_ptr 就功能而言可能是最简单的替代品。你可以在任何你可以使用 unique_ptr 的地方安全地使用它,并且它会起作用。由于增加了引用计数,它不会那么有效。但是,如果您正在寻找一个能够处理 unique_ptr 可以做的所有事情的简单替代品,那么这可能是您最好的选择。 (当然,shared_ptr 也可以做更多事情,但它也可以简单地用作 unique_ptr 的替代品。)
  • boost::scoped_ptr 类似于 unique_ptr 但不允许所有权转移。只要智能指针在其生命周期内保持独占所有权,它就可以很好地工作。
  • std::auto_ptr 的工作方式与 unique_ptr 非常相似,但有一些限制,主要是它不能存储在标准库容器中。如果您只是在寻找一个允许转移所有权的指针,但它并不意味着存储在容器中或复制,那么这可能是一个不错的选择。

关于c++ - unique_ptr boost 等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2953530/

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