Why is the first copy constructor called in the code below?

Why is B(B&) ctor called instead of B(const B&) when building object b1 ?

 #include <iostream> using namespace std; struct B { int i; B() : i(2) { } B(B& x) : i(xi) { cout << "Copy constructor B(B&), i = " << i << endl; } B(const B& x) : i(xi) { cout << "Copy constructor B(const B&), i = " << i << endl; } }; int main() { B b; B b1(b); } 
+4
source share
5 answers

13.3.3.2/3 says

Two implicit conversion sequences of the same form are indistinguishable conversion sequences if only the following rules apply:

- The standard conversion sequence S1 is a better conversion sequence than the standard conversion sequence S2 if:

S1 and S2 are binding bindings (8.5.3), and the types to which the links belong are the same type, with the exception of the top-level cv qualifiers, and the type to which the link initialized by S2 refers is more cv than the type to to which the link initialized S1 belongs. [Example:

 int f(const int &); int f(int &); ... int i; int j = f(i); // calls f(int&) 

In your case, since the argument is not const, the non-content version of the copy c-tor is selected because it matches better.

+2
source

This is due to the fact that overload resolution is applied, and since the constructor argument b1 is equal to b , and b is not a constant lvalue, then a constructor that accepts not const const lvlalue is selected. And this is the first. Interestingly, both are copy constructors, but your code will be equal to valid only with the latter.

+6
source

Because b is not const. Therefore, it is ideal for the first instance of ctor, so the compiler is used.

+5
source

because b not a constant.

+1
source

Try the following:

 int main() { const B b; B b1(b); } 

Also, this is a difficult decision that you have to use const or not;)

+1
source

Source: https://habr.com/ru/post/1392672/


All Articles