在按值返回时复制构造函数的奇怪行为

时间:2012-06-30 21:17:52

标签: c++ copy-constructor return-by-value

我测试了复制构造函数的行为,其中函数按值返回一个对象,我遇到了一个复制构造函数被调用的情况和一个不复制的情况。

请考虑以下代码:

class A {
public:
    A() {}
    A(const A& a) {
        cout << "Copy CTOR: " << "This address is " << this 
             << " input address is "<< &a <<       "\n";
    }
};

A returnMyself(A& a) {
    cout<<"Myself address is: "<< &a << "\n";
    return a;
}

A returnLocal(A& a) {
    A local;
    cout<<"local address in returnLocal is  "<< &local << "\n";
    return local;
}

int main () {
    A a;
    cout<<"Before returnMyself\n";
    returnMyself(a);
    cout<<"After returnMyself\n\n";

    cout<<"Before returnLocal\n";
    returnLocal(a);
    cout<<"After returnLocal\n";
}

main的输出是:

Before returnMyself.
Myself address is: 0x7fff6afd88f0.
Copy CTOR Invoked: This address is 0x7fff6afd88d8. Input address is 0x7fff6afd88f0.
After returnMyself.

Before returnLocal.
Local address in returnLocal is  0x7fff6afd88d0.
After returnLocal.

正如您所看到的,当我声明一个本地对象并返回它时,不会调用复制构造函数,而是返回一个调用复制构造函数的给定引用对象。

有没有人对此有解释?通常,从按函数返回的函数调用复制构造函数的情况是什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

这是copy elision。编译器非常聪明,可以优化该副本。