Consider the following code:
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(): a(5)
{
cout << "Constructor\n";
}
A(const A &b)
{
a = b.a;
cout << "Copy Constructor\n";
}
A fun(A a)
{
return a;
}
};
int main()
{
A a, c;
A b = a.fun(c);
return 0;
}
上述代码使用
g++ file.cpp
编译的输出结果为:Constructor
Constructor
Copy Constructor
Copy Constructor
以上代码使用
g++ -fno-elide-constructors file.cpp
编译的输出结果如下:Constructor
Constructor
Copy Constructor
Copy Constructor
Copy Constructor
我知道返回值优化。我的问题是副本构造函数的哪个调用被省略了(在返回期间的临时对象还是返回的对象被复制到b)?
如果省略的副本构造函数是用于创建b的那个,则如何创建b(因为在这种情况下也没有构造函数调用)?
如果我将行
A b = a.fun(c);
替换为 a.fun(c)
并使用第一种方法或第二种方法编译,那么副本构造函数仍然会被调用2次。所以,在上一段中解释的情况下,临时对象的副本构造函数被省略了,为什么在这种情况下它没有被省略?
std::cout << "Copy constructor: " << (void*)b << " to " << (void*)this << std::endl;
和std::cout << "Constructing " << (void*)this << std::endl
。如果您添加了C++11中的移动语义,将获得额外加分。 - IdeaHat