为什么 C++ 自动对象优化发生在此代码中

why c++ auto object optimization is happening in this code?

本文关键字:代码 优化 C++ 对象 为什么      更新时间:2023-10-16

为什么在这个程序中只创建了一个 A 对象?并且没有调用复制构造函数。这种优化叫什么?如果这是一个有效/已知的优化,那么对于多实例设计模式来说,它不会是一个麻烦吗?

#include <iostream>
#include <stdio.h>
using namespace std;
class A
{
    public:
        A () {
            cout << "in-- Constructor A" << endl;
            ++as;
        }
        A (const A &a) {
            cout << "in-- Copy-Constructor A" << endl;
            ++as;
        }
        ~A() {
            cout << "out --Constructor A" << endl;
            --as;
        }
        A & operator=(const A &a) {
            cout << "assignment" << endl;
            ++as;
            //return *this;
        }
        static int as;
};
int A::as = 0;

A fxn() {
    A a;
    cout << "a: " << &a << endl;
    return a;
}
int main() {
    A b = fxn();
    cout << "b: " << &b << endl;
    cout << "did destructor of object a in func fxn called?" << endl;
    return 0;
}

以上程序的输出

in-- Constructor A
a: 0x7fffeca3bed7
b: 0x7fffeca3bed7
did destructor of object a in func fxn called?
out --Constructor A

浏览链接 http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/它会帮助你。

这似乎是返回值优化的一个案例。这种优化在C++世界中是值得注意的,因为它被允许改变程序的可观察行为。它是为数不多的(如果不是唯一的话)允许这样做的优化之一,而且它来自返回副本被认为是弱点的日子。(使用移动语义和通常更快的机器,这现在不是一个问题。

基本上,编译器看到它将复制对象,因此它会在调用帧上为它分配空间,然后在那里构建它,而不是调用复制构造函数。