lundi 30 mai 2016

Only Constructor is called in this assignment [duplicate]

This question already has an answer here:

Look at this code snippet:

class Bar
{
public:
    Bar() { cout << "CTOR" << endl; }
    Bar(char* str) { cout << "SECOND CTOR" << endl; };
    Bar(const Bar& copy) { cout << "COPY CTOR" << endl; }
    Bar(const Bar&& move) { cout << "MOVE CTOR" << endl; }

    Bar& operator=(const Bar& other) { cout << "ASSIGNMENT" << endl; return Bar(); }
    Bar& operator=(Bar&& other) { cout << "MOVE ASSIGNMENT" << endl; return Bar(); }
};

Bar test()
{
    return Bar();
}

This class has:

  • Default constructor
  • Second constructor taking a char*
  • Copy Constructor
  • Move Constructor
  • Assignment Operator
  • Move Assignment

Now look at this:

int main()
{   
    Bar h = test();
}

The output is just:

CTOR

Why?

I'd have expected another Constructor call for the Bar object I'm constructing in the test() function.

Also, there's no trace of any Assignment operator or Move Assignment.

I don't understand what's going on...

Aucun commentaire:

Enregistrer un commentaire