为什么编译器在使用"无常量复制构造函数"时抱怨?

Why does the compiler complains when `none const copy constructor` is used?

本文关键字:quot 构造函数 复制 常量 编译器 为什么 无常      更新时间:2023-10-16

作为主题,下面的代码是正确的。

#include<iostream>
class ABC     
{  public:  
ABC() 
{
std::cout<< "default construction" << std::endl;
}
ABC(ABC& a) 
{
std::cout << "copy construction" << std::endl;
} 
};                         
int main()   
{  
ABC c1 = ABC(); 
}

它无法成功编译:

<source>: In function 'int main()': 
<source>:25:13: error: cannot bind non-const lvalue reference of type 'ABC&' to an rvalue of type 'ABC'
25 |    ABC c1 = ABC();
|             ^~~~~
<source>:10:14: note:   initializing argument 1 of 'ABC::ABC(ABC&)'
10 |     ABC(ABC& a)
|         ~~~~~^

但是,如果将ABC(ABC& a)替换为ABC(const ABC&),它可以编译。我知道它与关键字const有某种关系。但是我不知道为什么。

您可以在 https://godbolt.org/z/jNL5Bd 上检查它。我是C++新手。如果能在这个问题上得到一些帮助,我将不胜感激。

正如错误消息所说,临时ABC()不能绑定到非常量值引用,复制构造函数不能用于初始化ABC&。(临时变量可以绑定到常量或右值引用的左值引用。


PS:由于C++17代码将编译(这并不意味着复制构造函数对非常量采用左值引用是一种好方法(,因为可以保证复制省略,因此复制构造将被完全省略。

(强调我的(

在以下情况下,编译器需要省略类对象的复制和移动构造,即使复制/移动构造函数和析构函数具有可观察到的副作用。这些对象直接构造到存储中,否则它们将被复制/移动到存储中。复制/移动构造函数不需要存在或可访问