Move constructor on destructed object?

I have a piece of code

#include <iostream>

class A {
public:
    A() {
        std::cout << "Default constructor" << std::endl;
    }
    A(const A & other)
    {
        std::cout << "Copy constructor" << std::endl;
    }
    A(A && other)
    {
        std::cout << "Move constructor" << std::endl;
    }
    ~A()
    {
        std::cout << "Destructor" << std::endl;
    }
private:
    int i;
};

A && f()
{
    return A();
}

int main() {
    A a = f();
}

I tried running it and the output turns out to be

Default constructor
Destructor
Move constructor 
Destructor

My question is Why is destructor is called before the moved constructor? Does this also mean that second object was constructed with a destroyed value ?

Upvotes: 6

Views: 158

Answers (2)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29013

Returning a local variable from A && f() has the same problem as A & f(). They are both references. By the time you construct a in main(), the local variable has been destroyed. This results in a reference to a destroyed instance leading to undefined behavior.

If you want to move A() from f() to a in main simply return by value. Try using the following :

A f() {
    return A();
}

Upvotes: 6

debashish.ghosh
debashish.ghosh

Reputation: 123

The first A object was created in f's call stack frame. So when f returns control to main all the stack objects which were created inside f would have to be destroyed. That's why the first destructor was called.

Upvotes: 0

Related Questions