0

可能重复:
什么是复制省略和返回值优化?

根据昨天问的问题,我写了一个简单的测试代码:

class A
{
public:
    A(int)
    {
        cout<<"constructor\n";
    }
    A(const A&)
    {
        cout<<"copy constructor\n";
    }
};

int main()
{
    A(0);
    cout<<"------------------------\n";
    A(A(0));
    cout<<"------------------------\n";
    A(A(A(0)));
    cout<<"------------------------\n";
    A(A(A(A(0))));
    cout<<"------------------------\n";
    A(A(A(A(A(0)))));
    cout<<"------------------------\n";
    return 0;
}

输出:

constructor
------------------------
constructor
------------------------
constructor
copy constructor
------------------------
constructor
copy constructor
------------------------
constructor
copy constructor
copy constructor
------------------------

所以当构造函数调用或类型转换发生时说清楚是很奇怪的,有人可以解释一下吗?

4

0 回答 0