c++ - 为什么使用 `none const copy constructor` 时编译器会报错?

标签 c++ c++11 constructor copy-constructor move-semantics

作为主体,下面的代码是对的。

#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/

相关文章:

c++ - std::mutex 作为类成员,将类对象存储到容器中

c++ - 如何将对象添加到 std::vector<unique_ptr<obj>>?

c++ - 多级继承中的析构函数调用 (c++)

c - 为什么 __attribute__((constructor)) 在静态库中不起作用?

javascript - 使用 Javascript 构造函数进行原型(prototype)设计

c++ - 'void()' 中的 'auto f(params) -> decltype(..., void())' 有什么作用?

c++ - IEEE float 到精确的 base10 字符串

具有模板化类型结构问题的 C++ 函数模板参数

c++ - SFML 2.1 复制图像

c++ - 无法使用双指针作为函数参数传递二维数组