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

Move constructor on destructed object?

本文关键字:移动 构造函数 对象      更新时间:2023-10-16

我有一块代码

#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();
}

我尝试运行它,而输出结果为

Default constructor
Destructor
Move constructor 
Destructor

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

A && f()返回本地变量的问题与A & f()相同。它们都是参考。当您在main()中构造a时,局部变量已被破坏。这导致引用被破坏的实例导致不确定的行为。

如果您想将A()f()移动到main中的a,只需按值返回即可。尝试使用以下内容:

A f() {
    return A();
}

第一个A对象是在f的调用堆栈帧中创建的。因此,当f将控件返回到main时,将必须破坏f中创建的所有堆栈对象。这就是为什么称为第一个破坏者的原因。