如何让这个代码涉及unique_ptr进行编译?

时间:2010-04-21 23:55:10

标签: c++ c++11 rvalue-reference unique-ptr

#include <vector>
#include <memory>

using namespace std;

class A {
public:
    A(): i(new int) {}
    A(A const& a) = delete;
    A(A &&a): i(move(a.i)) {}

    unique_ptr<int> i;
};

class AGroup {
public:
    void                    AddA(A &&a) { a_.emplace_back(move(a)); }

    vector<A> a_;
};

int main() {
    AGroup ag;
    ag.AddA(A());
    return 0;
}

不编译...(说删除了unique_ptr的拷贝构造函数)

我尝试用前锋替换移动。不确定我是否做得对,但它对我不起作用。


[~/nn/src] g++ a.cc -o a -std=c++0x
/opt/local/include/gcc44/c++/bits/unique_ptr.h: In member function 'A& A::operator=(const A&)':
a.cc:6:   instantiated from 'void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, _Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]'
/opt/local/include/gcc44/c++/bits/vector.tcc:100:   instantiated from 'void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]'
a.cc:17:   instantiated from here
/opt/local/include/gcc44/c++/bits/unique_ptr.h:219: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>& std::unique_ptr<_Tp, _Tp_Deleter>::operator=(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>]'
a.cc:6: error: used here
In file included from /opt/local/include/gcc44/c++/vector:69,
                 from a.cc:1:
/opt/local/include/gcc44/c++/bits/vector.tcc: In member function 'void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, _Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]':
/opt/local/include/gcc44/c++/bits/vector.tcc:100:   instantiated from 'void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]'
a.cc:17:   instantiated from here
/opt/local/include/gcc44/c++/bits/vector.tcc:314: note: synthesized method 'A& A::operator=(const A&)' first required here

1 个答案:

答案 0 :(得分:3)

您的标准库可能(尚未)定义unique_ptr<T>::unique_ptr(unique_ptr &&)。我在4.5中检查了我的标题,它就在那里,所以也许尝试升级。

当找不到移动构造函数时,它会查找复制构造函数并将其删除。

我编译时会遇到其他错误。

编辑:让它发挥作用。我不明白为什么你必须move一个已经是左值引用的对象,但是你做到了。唯一的问题是缺少分配运营商。

#include <vector>
#include <memory>

using namespace std;

class A {
public:
    A(): i(new int) {}
    A(A const& a) = delete;
    A &operator=(A const &) = delete;
    A(A &&a): i(move(a.i)) {}
    A &operator=(A &&a ) { i = move(a.i); }

    unique_ptr<int> i;
};

class AGroup {
public:
    void                    AddA(A &&a) { a_.emplace_back(move(a)); }

    vector<A> a_;
};

int main() {
    AGroup ag;
    ag.AddA(A());
    return 0;
}