C++ unique_ptr 提升等效吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2953530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:36:21  来源:igfitidea点击:

unique_ptr boost equivalent?

c++boostc++11unique-ptr

提问by Clark Gaebel

Is there some equivalent class for C++1x's std::unique_ptr in the boost libraries? The behavior I'm looking for is being able to have an exception-safe factory function, like so...

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.
}

EDIT: Right now, I'm using this hack, which seems like the best I can get at this point...

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

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.
}

回答by jalf

It's not possible to create something like unique_ptrwithout C++0x (where it's part of the standard library, and so Boost doesn't need to provide it).

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

Specifically without rvalue references, which are a feature in C++0x, a robust implementation of unique_ptris impossible, with or without Boost.

特别是如果没有右值引用(C++0x 中的一个特性)unique_ptr,无论是否使用 Boost ,都无法实现 的健壮实现。

In C++03, there are a few possible alternatives, although each have their flaws.

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

  • boost::shared_ptris probably the simplest replacement in terms of capabilites. You can safely use it anywhere you'd otherwise use a unique_ptrand it'd work. It just wouldn't be as efficient, because of the added reference counting. But if you're looking for a simple drop-in replacement that's able to handle everything unique_ptrcan do, this is probably your best bet. (Of course, a shared_ptrcan do a lot more as well, but it can also simply be used as a drop-in replacement for unique_ptr.)
  • boost::scoped_ptris similar to unique_ptrbut does not allow transfer of ownership. It works great as long as the smart pointer is meant to retain exclusive ownership throughout its lifetime.
  • std::auto_ptrworks very similar to unique_ptr, but has a few limitations, mainly that it can not be stored in standard library containers. If you're simply looking for a pointer that allows transfer of ownership, but which is not meant to be stored in containers or copied around, this is probably a good bet.
  • boost::shared_ptr就功能而言,可能是最简单的替代品。您可以安全地在任何地方使用它,否则unique_ptr它会使用 a并且它会起作用。由于添加了引用计数,它的效率不会那么高。但是,如果您正在寻找能够处理所有事情的简单替代品unique_ptr,这可能是您最好的选择。(当然, ashared_ptr也可以做更多的事情,但它也可以简单地用作 的替代品unique_ptr。)
  • boost::scoped_ptr类似于unique_ptr但不允许转让所有权。只要智能指针旨在在其整个生命周期内保持独占所有权,它就可以很好地工作。
  • std::auto_ptr与 非常相似unique_ptr,但有一些限制,主要是它不能存储在标准库容器中。如果您只是在寻找一个允许所有权转移的指针,但不打算将其存储在容器中或四处复制,那么这可能是一个不错的选择。

回答by Adam Romanek

Starting from Boost 1.57there's an official unique_ptrimplementation in Boost.Movelibrary.

Boost 1.57开始unique_ptrBoost.Move库中有一个官方实现。

From the documentation:

文档

(...) a drop-in replacement for std::unique_ptr, usable also from C++03 compilers.

(...) std::unique_ptr 的替代品,也可用于 C++03 编译器。

The code is available in <boost/move/unique_ptr.hpp>header file and lives in boost::movelibnamespace. Moreover, Boost.Move library provides make_unique()factory function in <boost/move/make_unique.hpp>, also in boost::movelibnamespace.

代码在<boost/move/unique_ptr.hpp>头文件中可用并且位于boost::movelib命名空间中。此外,Boost.Move 库make_unique()<boost/move/make_unique.hpp>,也在boost::movelib命名空间中提供工厂函数。

Hence the example from the question could be implemented this way:

因此,问题中的示例可以这样实现:

#include <boost/move/unique_ptr.hpp>

using boost::movelib::unique_ptr;

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

See a live example on Wandbox. Note that the code compiles fine with gcc 4.6.4 in C++98 mode (!).

请参阅Wandbox 上的现场示例。请注意,该代码在 C++98 模式 (!) 下使用 gcc 4.6.4 编译得很好。

What's interesting in boost::movelib::unique_ptrwhen applied to your case with base/derived classes, the implementation provides a compile-time check for the declaration of a virtual destructor in the base class. If you happen to omit it the code won't compile(click the "Run (...)" button to see the compiler error message).

boost::movelib::unique_ptr当应用到基类/派生类的情况时,有趣的是,该实现为基类中的虚拟析构函数的声明提供了编译时检查。如果您碰巧省略了它,代码将无法编译(单击“运行 (...)”按钮以查看编译器错误消息)。

One minor issue is that includes come from boost/movedirectory but the code lives in boost::movelibnamespace (subtle difference but can be annoying).

一个小问题是包含来自boost/move目录但代码位于boost::movelib命名空间中(细微差别但可能很烦人)。

See also a thread on boost mailing listfor more details.

另请参阅有关 boost 邮件列表的线程以获取更多详细信息。

Thanks to Ion Gazta?aga for this absolutely unique and useful piece of code.

感谢 Ion Gazta?aga 提供了这段绝对独特且有用的代码。

回答by Michael Burr

You might want to try Howard Hinnant's 'proof of concept' unique_ptr<>implementation for C++03 (disclaimer - I haven't):

您可能想尝试unique_ptr<>C++03 的Howard Hinnant 的“概念证明”实现(免责声明 - 我还没有):

One of his examples is returning a unique_ptr<int>:

他的一个例子是返回一个unique_ptr<int>

unique_ptr<int> factory(int i)
{
    return unique_ptr<int>(new int(i));
}

回答by fbrereto

How about unique_ptrfrom the interprocesslibrary?

如何unique_ptr图书馆吗?

回答by deft_code

I've used Howard Hinnant's unique_ptr. If you are not really good at reading crazy metaprogramming errors from you compiler you might want to steer clear. It however does act just like a unique_ptr in 90% of the cases.

我用过 Howard Hinnant 的unique_ptr。如果您不太擅长从编译器中读取疯狂的元编程错误,则可能需要避开。然而,在 90% 的情况下,它确实像 unique_ptr 一样。

Otherwise I'd suggest passing paramters as boost::scoped_ptr&and swap internally to steal ownership. To get unique_ptr style return values use an auto_ptr. Capture the auto_ptrreturn value in a shared_ptror scoped_ptrto avoid using the auto_ptrdirectly.

否则,我建议将参数传递为boost::scoped_ptr&并在内部交换以窃取所有权。要获得 unique_ptr 样式的返回值,请使用auto_ptr. 捕捉auto_ptr的返回值shared_ptrscoped_ptr在使用避免auto_ptr直接。