简体   繁体   中英

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.

You could check it on https://godbolt.org/z/jNL5Bd . I am a novice in C++.I would be grateful to have some help with this question.

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. (Temporaries could be bound to lvalue-reference to const or 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.

(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 . 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 :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM