对于已弃用的 std::auto_ptr,c++11 标准的等效项是什么?

What's c++11 standard's equivalent for the deprecated std::auto_ptr?

本文关键字:标准 c++11 是什么 std auto ptr      更新时间:2023-10-16

我有一些代码使用std::auto_ptr,并在编译时对不推荐使用的std::auto_ptr(Suse Linux 12.2上的GCC 4.7.1)发出丑陋的警告。

因此,我尝试了以下方法(因为我找到了一些来源,认为std::unique_ptr应该是适当的等价物)

template<typename T>
struct AutoPtr
{
#ifdef COMPILE_FOR_CX11
    typedef std::unique_ptr<T> Type;
#else
    typedef std::auto_ptr<T> Type;
#endif
};

并用AutoPtr<T>::Type替换了对std::auto_ptr<T>的任何引用,但在使用此选项时出现编译错误。

我很确定我想在这些代码中使用类似std::auto_ptr的东西,我知道它的罪魁祸首和不足。当使用std::unique_ptr时,我得到的错误似乎与构造问题有关。

附带说明:用于构造的最后一个类是T的继承类型,代码看起来像:

class MockClass;
class Client
{
public:
    Client();
    Client(const Client& rhs);
private:
    mutable AutoPtr<MockClass>::Type embeddedMock;
};

Client::Client()
: embeddedMock(new ::testing::NiceMock<MockClass>())
//             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Getting errors here!
{
}

Client::Client(const Client& rhs)
: embeddedMock(rhs.embeddedMock)
{
}

那么,我可以在这里使用c++11集合中的什么是完全兼容的智能指针呢?

unique_ptrauto_ptr的C++11替换工具。然而,这并不是一个简单的替换,因为auto_ptr在复制语义上具有所有权转移,而unique_ptr强制您显式地转移所有权。当你有这样的东西时:

auto_ptr<Foo> x(new Foo());
// ...
auto_ptr<Foo> y = x;
// ...
bar( y ); // copies y into bar(), transferring ownership

要使用unique_ptr,您需要将move()添加到所有权转移站点:

unique_ptr<Foo> x(new Foo());
// ...
unique_ptr<Foo> y = move(x);
// ...
bar( move(y) );

编辑:

如果不知道你会遇到什么特定的错误,很难判断你的默认构造函数为什么无法编译。但是,除非添加了move,否则副本构造函数应该无法使用unique_ptr进行编译。