mardi 27 août 2019

move constructor is not getting called when I am calling constructor explicitly as a parameter

I am trying to learn about move constructors. I wrote the below program.

#include <iostream>
#include <algorithm>

using namespace std;

class myclass {
    public:
        myclass() { 
            cout << "In Constructor" << endl;
        }

        ~myclass() {
            cout << "In Destructor" << endl;
        }

        myclass(const myclass &obj) {
            cout << "In Copy Constructor" << endl;
        }

        myclass(myclass &&obj) {
            cout << "In Move Constructor" << endl;
        }
};

int main()
{
    myclass obj = myclass();       // Line 1
    myclass obj(myclass());        // Line 2
}

Line 1 is working as expected, move constructor is getting called. But for line 2, nothing is happening. Not even constructor is getting called. I thought that move constructor will be called for line 2 also. But no function is getting called. I know if I call the constructor explicitly, the object will be destroyed at the end of the expression. But I am not sure why even constructor is not getting called. Can any one please let me know what is wrong with Line 2?

Aucun commentaire:

Enregistrer un commentaire