c++ - 为什么这里涉及移动构造函数

标签 c++ c++11 initialization copy-elision

我有这段C++代码:

class Args {};

class MyClass {
  public:
  MyClass(Args& a) {}
  MyClass(MyClass &&) = delete;
};

int main() {

  Args a;
  MyClass c1 = MyClass(a);
  MyClass c2 = a;
  MyClass c3(a);

  return 0;
}

这不会编译,因为对象 c1c2 的构造似乎涉及类的移动构造函数:

错误:使用已删除的函数“MyClass::MyClass(MyClass&&)”

似乎编译器想要创建临时对象,然后将它们移动到c1c2。为什么会这样?这三个语句不应该只调用 MyClass(Args& a) 构造函数吗?

另一方面,如果我确实创建了移动构造函数,程序可以正常编译并且永远不会调用移动构造函数!!!

最佳答案

参见 copy elision :

Under the following circumstances, the compilers are permitted, but not required to omit the copy- and move- (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. This is an optimization: even when it takes place and the copy-/move-constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed.

自 C++17 起:

They need not be present or accessible, as the language rules ensure that no copy/move operation takes place, even conceptually.

关于c++ - 为什么这里涉及移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059991/

相关文章:

c# - 为什么 C# 局部变量应该直接赋值,即使它是默认值?

c++ - 切片网格的算法或软件

c++ - 使用 scanf 进行输入过滤

file - 分别在二进制和文本文件中存储数字需要多少字节

python - 为什么我的缓冲区输出被切碎了? C++套接字编程

java - long 1l,float 1f,double 1d,byte呢?

c++ - 复制构造函数和组合

C++ 如何给抽象类中的成员变量一个默认值?

mysql - 在 MySQL 8.0+ 中使用 MySQL 驱动程序在 MySQL 语句中传递 C++ 变量

C++ - 使用 `this` 在类级别初始化成员与在构造函数中使用 `this` 之间有什么区别吗?