考虑下面的代码的返回值初始化的对象时不叫:复制构造与功能
#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 <<“复制构造函数:”<<(void *)b <<“to”<<(void *)this << std :: endl;' ,和'std :: cout <<“构造”<<(void *)this << std :: endl'。如果你在C++中添加移动,奖励点数11。 – IdeaHat 2014-11-14 19:20:39