c++ - "error: use of deleted function"在 move 构造函数中对 unique_ptr 调用 std::move 时

标签 c++ c++11 move

#include <memory>

class A
{
public:
    A()
    {
    }

    A( const A&& rhs )
    {
        a = std::move( rhs.a );
    }

private:
    std::unique_ptr<int> a;
};

此代码无法使用 g++ 4.8.4 编译并抛出以下错误:

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>
::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_de
lete<int>]’
     a = std::move( rhs.a );
       ^

我知道 unique_ptr 的复制构造函数和复制赋值构造函数已删除且无法调用,但我认为通过使用 std::move 在这里我会调用 move 赋值构造函数。 The official documentation甚至显示正在完成这种类型的任务。

我没有看到我的代码中有什么错误?

最佳答案

A( const A&& rhs )
// ^^^^^

删除const——从一个对象 move 是破坏性的,所以你不能从一个const对象 move 是公平的。

关于c++ - "error: use of deleted function"在 move 构造函数中对 unique_ptr 调用 std::move 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621665/

相关文章:

c++ - 使用处理 IO 队列的线程提升线程池

c++ - 定义专用模板类构造函数时避免重复

c++ - MSVC10 中的奇怪编译器错误

svn - 无需 checkout 即可在存储库中 move SVN 项目

python - 按创建/修改日期查找文件,然后 move 到 Python 中的另一个目录

c++ - 为什么链接器在虚拟情况下给我一个错误,但在非虚拟情况下却没有?

c++ - 在没有硬件加速的情况下使用 ffmpeg (C++)

C++ 使用 strtok 拆分字符串忽略最后一个条目

Javascript setInterval 不适用于此。对象

c++ - GCC 4.7 中是否存在错误。 2's implementation of shared_ptr' s(模板化)赋值运算符?