c++ - C++中局部变量和返回变量的构造和析构

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

#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,未调用移动(或复制)构造函数. 编译器直接在返回值处构造局部变量。

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

编译器在某些条件下允许进行此类优化,这些条件在标准中有所提及。但引用 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.

关于c++ - C++中局部变量和返回变量的构造和析构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45649373/

相关文章:

c++ - 在构造函数中使用 'new'? C++

c++ - 标量类型和未定义行为的析构函数调用

c++ - 如何使用指针 vector 实现类析构函数 C++

c++ - 当涉及多个异常处理时,何时调用析构函数?

c++ - 是否可以在 C 中使用指针来访问文本或内核部分?

c++ - 如何在字符串中添加换行符?

javascript - 如何将原型(prototype)分配给已经构建的对象?

javascript - ES6 super() 在构造函数中实际上做了什么?

c++ - 如何检查文件中是否没有要读取的数据

c++ - 在 C++ STL 映射中,删除具有重复值的条目