在被破坏的对象上移动构造函数?

Вит*_*аев 6 c++ move-semantics

我有一段代码

#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();
}
Run Code Online (Sandbox Code Playgroud)

我尝试运行它,输出结果是

Default constructor
Destructor
Move constructor 
Destructor
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么在移动的构造函数之前调用析构函数?这是否也意味着第二个对象是用破坏的价值构建的?

Fra*_*eux 6

从中返回局部变量A && f()具有与之相同的问题A & f().它们都是参考文献.在构造amain(),局部变量已被破坏.这会导致对被破坏的实例的引用,从而导致未定义的行为.

如果要移动A()f()amain通过简单地返回值.尝试使用以下内容:

A f() {
    return A();
}
Run Code Online (Sandbox Code Playgroud)