I have the following code:
#include<iostream>
using namespace std;
class A{
private:
int x;
public:
A(){x=10;}
A(int m){x=m; cout << "int m constructor" << m << endl;}
A(A& a){cout << "copy constructor:"<<a.x<<"\n"; x=a.x;}
A(A&& a){cout <<"move constructor:"<<a.x<<"\n"; x=a.x;}
};
int main(){
A a(100);
A b = a;
A d = A(30);
}
which outputs the following:
int m constructor100
copy constructor:100
int m constructor30
I was expecting it to output
int m constructor100
copy constructor:100
copy constructor:30
because the constructor function (A(30)
) is called.
But somehow the compiler optimises it?
Also A d = A(A(30))
also prints int m constructor30
.
Is there some compiler optimization happening here?