Move constructor to destroyed 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 to run it, and the output is

Default constructor
Destructor
Move constructor 
Destructor

My question is: why is the destructor called before the moved constructor? Does this mean that the second object was built with the value destroyed?

+6
source share
2 answers

Returning a local variable from A && f()has the same problem as A & f(). They are both links. When you create ain main(), the local variable will be destroyed. This leads to a reference to the destroyed instance, resulting in undefined behavior.

A() f() a main, . :

A f() {
    return A();
}
+6

A f. , f main, , f, . .

0

Source: https://habr.com/ru/post/1016559/


All Articles