为什么编译器在使用"无常量复制构造函数"时抱怨?
Why does the compiler complains when `none const copy constructor` is used?
作为主题,下面的代码是正确的。
#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代码将编译(这并不意味着复制构造函数对非常量采用左值引用是一种好方法(,因为可以保证复制省略,因此复制构造将被完全省略。
(强调我的(
在以下情况下,编译器需要省略类对象的复制和移动构造,即使复制/移动构造函数和析构函数具有可观察到的副作用。这些对象直接构造到存储中,否则它们将被复制/移动到存储中。复制/移动构造函数不需要存在或可访问:
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- "非静态数据成员之前需要构造函数" - 我是否使用"boost::variant"