vendredi 11 juin 2021

Why doesn't NRVO work with move constructor in visual studio 2019, msvc 1929?

There is a class as follow:

class HeavyObject
{
public:
    HeavyObject() { cout << "Constructor\n"; }
    ~HeavyObject() { cout << "Destructor\n"; }
    HeavyObject(HeavyObject const&) { cout << "Copy Constructor\n"; }
    HeavyObject& operator=(HeavyObject const&) { cout << "Assignment Operator\n"; return *this; }
    HeavyObject(HeavyObject&&) { cout << "Move Constructor\n"; }
private:
    // many members omitted...
};

Then i test NRVO:

HeavyObject func()
{
    HeavyObject o;
    return o;
}

int main()
{
    HeavyObject o = func();
    return 0;
}

I think the output is :

Constructor
Destructor

But the real output is:

Constructor
Move Constructor
Destructor
Destructor

Why?

Aucun commentaire:

Enregistrer un commentaire