c++ - 如果我们只定义复制构造函数/操作=,为什么移动构造函数/移动赋值没有隐式声明和定义为删除?

标签 c++ c++11

根据 C++ 标准 12.8.7:

If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted;

和 12.8.18

If the class definition declares a move constructor or move assignment operator, the implicitly declared copy assignment operator is defined as deleted;

我想知道为什么移动构造函数/移动赋值没有隐式声明和定义为已删除(在这种情况下,C++11 标准不会生成隐式声明的移动构造函数/移动赋值),如果我们只定义复制构造函数或复制赋值运算符?

最佳答案

如果是这种情况,那么使用右值作为构建或赋值的源将导致编译错误,而不是回退到拷贝。

不存在的函数(显然)不参与重载决策。定义为已删除的函数确实正常参与重载决策;如果选择它,编译会导致错误。

此代码 compiles :

struct Normal
{
    Normal() {}

    Normal(const Normal &) {}
};


int main()
{
    Normal n(Normal{});
}

虽然此代码 results in an error :

struct Deleted
{
    Deleted() {}

    Deleted(const Deleted &) {}

    Deleted(Deleted&&) = delete;
};


int main()
{
    Deleted d(Deleted{});
}

关于c++ - 如果我们只定义复制构造函数/操作=,为什么移动构造函数/移动赋值没有隐式声明和定义为删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28545644/

相关文章:

c++ - 将大对象放在堆上的最佳方法是什么?

c++ - 具有比较器功能和自定义参数的模板

c++ - C/C++如何知道动态分配的数组有多长

c++ - 为什么通过 gSOAP 发送二进制数据太慢了?

c++ - 如何使用 <array> header 声明二维数组?

multithreading - 动态分配的实现类 std::async-ing 其成员

c++ - Htoi 10 位数字的输出不正确

c++ - VC++的迭代器声明

c++ - 在实时环境中仍然不希望出现异常吗?

c++ - 避免默认参数异常