1

I have some code that uses std::auto_ptr and gives ugly warnings about deprecated std::auto_ptr (GCC 4.7.1 on Suse Linux 12.2) when compiling.

So I have tried the following (since I found some source that states std::unique_ptr should be the appropriate equivalent)

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

and replaced any references to std::auto_ptr<T> with AutoPtr<T>::Type, but got compile errors when using this option.

I'm pretty sure I want to use something like std::auto_ptr at these pieces of code and I'm aware about the culprits and deficiencies of it. The errors I get seem to correlate about construction issues when std::unique_ptr is used.

As a side note: The final class used for construction is an inheriting type of T, the code looks like:

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)
{
}

So what's a full compliant smart pointer from the c++11 set, I can use here?

4

1 回答 1

9

unique_ptrauto_ptr. 但是,它不是直接替代品,因为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) );

编辑:

在不知道您遇到什么具体错误的情况下,很难说出您的默认构造函数为何无法编译。unique_ptr但是,除非move添加了,否则您的复制构造函数应该无法编译。

于 2013-07-12T21:24:28.497 回答