4、复制构造函数在不同编译器中的表现

class A {
public:
	int x;
	A(int x_):x(x_)
	{ cout << x << " constructor called" << endl; }
	A(const A & a ) { //本例中dev需要此const其他编译器不要
		x = 2 + a.x;
		cout << "copy called" << endl;
	}
	~A() { 
		cout << x << " destructor called" << endl;
	}
};

A f( ){ 
	A b(10); 
	return b; 
}

int main( ){
	A a(1);
	a = f();
	return 0;
}

/*
dev C++输出结果:
1 constructor called
10 constructor called
10 destructor called
10 destructor called

Visual Studio输出
结果:
1 constructor called
10 constructor called
copy called  				//f()执行return语句时,在函数作用域之外创建一个临时对象,这个临时对象用返回的对象进行初始化。这个临时对象额创建就会导致复制构造函数被调用。临时对象的值被赋值给a(这里是赋值操作)。
10 destructor called		//返回值临时对象被销毁
12 destructor called		//由于执行过一次复制构造函数,因此原本的10被+了2。
12 destructor called		//由于执行过一次复制构造函数,因此原本的10被+了2。
*/

这个例子说明dev出于优化目的并未生成返回值临时对象。而VS无此问题。

原文地址:https://www.cnblogs.com/lasnitch/p/12764283.html