作为主体,下面的代码是对的。
#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()
不能绑定(bind)到非 const 的左值引用,复制构造函数采用 ABC&
不能用于初始化。 (临时对象可以绑定(bind)到 const 或 rvalue-reference 的左值引用。)
PS:由于 C++17 代码可以编译(这并不意味着复制构造函数对非 const 进行左值引用是一种好方法),因为 copy elision保证,复制结构将被完全省略。
(强调我的)
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
关于c++ - 为什么使用 `none const copy constructor` 时编译器会报错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62098565/