【问题标题】:Constructing and Destructing of local variable and return variable in C++C++中局部变量和返回变量的构造和析构
【发布时间】:2018-01-20 19:23:30
【问题描述】:
#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()?

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

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

【问题讨论】:

    标签: c++ constructor destructor move-constructor copy-elision


    【解决方案1】:

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

    此类优化也称为 RVO(返回值优化)。

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

    解释标准的合法(可以说是有毒的)散文,[...] 编译器可能会省略对本地对象的复制(或移动) 在一个 如果 (1) 本地对象的类型与本地对象的类型相同,则按值返回的函数 由函数返回,并且 (2) 本地对象就是返回的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 2020-06-22
      • 2021-11-07
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多