Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When both move and copy constructor is present, which one will be called?

Below is class A which is full of different type of constructor. If i comment the move constructor, then the copy constructor is called twice : once for passing an object to function fun by value and other by returning from the same function.

Code Snippet

class A {

int x;

public :
A() {
    cout<<"Default Constructor\n";
}

A(A&& a) : x(a.x){
    cout<<"Move Constructor\n";
    a.x=0;
}

A(const A& a){
    x=a.x;
    cout<<"Copy Constructor\n";
}

A fun(A a){
    return a;
}

};

int main() {

A a;
A b;
A c;
c=a.fun(b);

}

OUTPUT :

Default Constructor

Default Constructor

Default Constructor

Copy Constructor

Move Constructor

However, if the move constructor is present, it is called rather than copy constructor. Can anyone eloborate this with a good example, so that i will be clear on this concept.

I would appreciate your help.Thanks.

like image 519
Gayathri Avatar asked Dec 26 '14 18:12

Gayathri


1 Answers

The standard allows a special case for the case where the expression in the return statement is an automatic duration variable. In this case, the constructor overloads are picked as if the expression in the return was an rvalue.

To be more precise, if the expression in the return statement was an automatic duration variable which was eligible for copy elision, or would be if you ignored the fact that it was a function argument, then, the compiler is required to treat it as an rvalue for the purpose of overload resolution. Note that in C++11, the return statement's expression needs to have the cv-unqualified type as the functions return type. This has been relaxed somewhat in C++14.

For example, in C++11, the following code calls the copy constructor of A, instead of the move constructor:

class A
{
};

class B
{
public:
B(A a) : a(std::move(a)){}
A a;
};

B f(A a)
{
return a;///When this is implicitly converted to `B` by calling the constructor `B(a)`, the copy constructor will be invoked in C++11. This behaviour has been fixed in C++14.
}
like image 175
Pradhan Avatar answered Oct 25 '22 18:10

Pradhan