根据 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/