[英]Why does the compiler complains when `none const copy constructor` is used?
As the subject, the code below is right.作为主体,下面的代码是对的。
#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();
}
It could not compile successfully:它无法成功编译:
<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)
| ~~~~~^
However, it could compile if replace the ABC(ABC& a)
by ABC(const ABC&)
.I know it has some relation with the keyword const
.But i could not figure out why.但是,如果将ABC(ABC& a)
替换为 ABC ABC(const ABC&)
,它可以编译。我知道它与关键字const
有一些关系。但我不知道为什么。
You could check it on https://godbolt.org/z/jNL5Bd .您可以在https://godbolt.org/z/jNL5Bd上查看它。 I am a novice in C++.I would be grateful to have some help with this question.我是 C++ 的新手。如果能在这个问题上得到一些帮助,我将不胜感激。
As the error message said, the temporary ABC()
can't be bound to lvalue-reference to non-const, the copy constructor taking ABC&
can't be used for initialization.正如错误消息所说,临时ABC()
不能绑定到非 const 的左值引用,采用ABC&
的复制构造函数不能用于初始化。 (Temporaries could be bound to lvalue-reference to const or rvalue-reference.) (临时对象可以绑定到 const 或 rvalue-reference 的左值引用。)
PS: Since C++17 the code would compile (which doesn't mean the copy constructor taking lvalue-reference to non-const is a good manner), because copy elision is guaranteed, the copy construction would be elided completely. PS:由于C++17代码可以编译(这并不意味着复制构造函数对非 const 进行左值引用是一种好方法),因为保证了复制省略,所以复制构造将被完全省略。
(emphasis mine) (强调我的)
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 .在以下情况下,编译器需要省略 class 对象的复制和移动构造,即使复制/移动构造函数和析构函数具有可观察到的副作用。 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 :复制/移动构造函数不需要存在或可访问:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.