C++中局部变量和return变量的构造和析构

Constructing and Destructing of local variable and return variable in C++

#include <iostream>
using namespace std;

class A {
public:
    A() {
        cout << "A()" << endl;
    }
    A(const A& a) {
        cout << "A(const A& a)" << endl;
    }
    A(A&& a) {
        cout << "A(A&& a)" << endl;
    }
    A& operator=(const A& a) {
        cout << "operator=(const A& a)" << endl;
        return *this;
    }
    A& operator=(A&& a) {
        cout << "operator=(A&& a)" << endl;
        return *this;
    }
    ~A() {
        cout << "~A()" << endl;
    };
};

A foo() {
    A a;
    return a;
}

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

编译:

clang++ test.cpp -o test -std=c++11

输出:

A()
~A()

为什么输出中只有一对 A() 和 ~A()?

为什么不调用移动构造函数?

编译器是否做了一些代码优化?

由于 Copy Elision,未调用移动(或复制)构造函数。 编译器直接在return值处构造局部变量。

此类优化也称为 RVO(Return 价值优化)。

编译器在某些条件下允许进行此类优化,标准中提到了这些条件。但是对于这些条件,引用 Effective Modern C++ by Scott Meyers 的第 25 项可能更方便(不像标准中那样严格的信息,但可能更有效地吸收):

Paraphrasing the legalistic (arguably toxic) prose of the Standard, [...] compilers may elide the copying (or moving) of a local object in a function that returns by value if (1) the type of the local object is the same as that returned by the function and (2) the local object is what’s being returned.