Shirley Feng Shirley Feng - 1 year ago 84
C++ Question

Neither Default Constructor nor Copy Constructor is called when using anonymous object

Below is the snippet aimed to test the constructors. It was run in VS 2015.

In my opinion, "B b(B())" has the same function as "B b = B()", however, my code seems to say that they behave different.

I know there's copy elision by compiler optimization, but I think the default constructor should be called at least when execute "B b(B())".
Can anyone help point out where my misunderstood is?

class B
B() {
x = new int[100];
cout << "default constructor!"<<" "<<i << endl;
cout << "x address:" << x << endl << "--------" << endl;
B(const B &b) //copy constructor
cout << "Copy constructor & called " << i<< endl
<< "--------" << endl;
B(B &&b)//move constructor
x = b.x;
b.x = nullptr;
cout << "Copy constructor && called" << i << endl
<<"x address:"<< x << endl << "--------" << endl;

void print()
cout << "b address:" << x << endl << "--------" << endl;
static int i;
int *x;
int B::i = 0;

int main()
B b1; //default constructor
B b2 = B(); //default constructor only
B b3(B()); //????nothing called... why???
B b4 = b2; //copy constructor
B b5 = move(b2); //move constructor

return 0;

enter image description here

Answer Source

Note that B b(B()) is a function declaration, not a variable definition at all, then no constructor would be called.

According to Most vexing parse, B b(B()) is a function declaration, for a function named b which returns an object of type B and has a single (unnamed) parameter which is a pointer to function returning type B and taking no parameter.

You can solve it by using braces (list initlization (since C++11)), like

B b1( B{} );
B b2{ B() };
B b3{ B{} };  // preferable from C++11
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download