Implicit conversions and copy constructors

Update: The proposed duplicate resolves only part of this question. The key to understanding what is happening (the fact that a temporary link is first created) is not explained there.

This is my first time with implicit conversions, so I wrote this:

class A {};

class B {
public:
    B(A& other) {}
    // Copy constructor
    B(const B& other) {}
};

int main() {
    A foo;
    B bar = foo;
}

This compiles as expected, but if I remove it const, my compiler (gcc version 4.8.4) throws at destination, with an error message that I cannot understand:

test.cc: In functionint main()’:
test.cc:12:13: error: no matching function for call toB::B(B)’
     B bar = foo;
             ^
test.cc:12:13: note: candidates are:
test.cc:7:5: note: B::B(B&)
     B(B& other) {}
     ^
test.cc:7:5: note:   no known conversion for argument 1 from ‘B’ to ‘B&’
test.cc:5:5: note: B::B(A&)
     B(A& other) {}
     ^
test.cc:5:5: note:   no known conversion for argument 1 from ‘B’ to ‘A&’

Is this C ++ code? Why does he say no matching function for call to ‘B::B(B)’when I try to appoint Afor a start?

+4
source share
2 answers

B bar = foo copy-initialization: ( a B vs A), , -. :

B bar = B(foo);

const -, , rvalue lvalue. Rvalues ​​ const lvalue , .

, . :

B bar(foo);
+5

B bar = foo;

:

:

B(A& other) {}

:

B(B& other) {}

.

, .

B bar( foo );

, . .

, copy/move , . . , copy/move .

, B

class A {};

class B {
public:
    B(A& other) { std::cout << "B::B( A & )" << std::endl; }
    // Copy constructor
    B(const B& other) { std::cout << "B::B( const B & )" << std::endl; }
};

int main()
{
    A foo;
    B bar = foo;
}

B::B( const B & )

.

,

class A {};

class B {
public:
    B(A& other) { std::cout << "B::B( A & )" << std::endl; }
    // Copy constructor
private:
    B(const B& other) { std::cout << "B::B( const B & )" << std::endl; }
};

int main()
{
    A foo;
    B bar = foo;
}

( MS V++.:))

+7

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


All Articles