Shirley Feng
Shirley Feng

Reputation: 143

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
{
public:
    B() {
        ++i;
        x = new int[100];
        cout << "default constructor!"<<" "<<i << endl;
        cout << "x address:" << x << endl << "--------" << endl;
    }
    B(const B &b)  //copy constructor
    {   
        ++i;
        cout << "Copy constructor & called " << i<< endl 
            << "--------" << endl;
    }
    B(B &&b)//move constructor
    {
        x = b.x;    
        ++i;
        b.x = nullptr;
        cout << "Copy constructor && called" << i << endl 
            <<"x address:"<< x << endl << "--------" << endl;

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


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

    return 0;
}

enter image description here

Upvotes: 2

Views: 276

Answers (1)

songyuanyao
songyuanyao

Reputation: 173024

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

Upvotes: 4

Related Questions