Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 953
Виталик Бушаев Avatar asked Apr 14 '17 14:04

Виталик Бушаев


1 Answers

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();
}
like image 55
François Andrieux Avatar answered Nov 04 '22 16:11

François Andrieux