如果一个函数返回类类型,在编译器无优化的情况下,如果函数返回值不用于赋值或初始化变量,则调用类的拷贝构造函数将返回值赋给一个临时变量;如果返回值用于赋值,则先调用类的拷贝构造函数将返回值赋给一个临时变量,再调用赋值运算符,将临时变量赋值给被赋值的变量;如果返回值用于初始化类变量,则函数返回时,调用类的拷贝构造函数将返回值拷贝给被初始化的变量。以上三种情况参见下面的测试代码和输出:
#include <iostream>
#include <string>
using namespace std;
class A {
static int count;
int indent;
public:
A () : indent (count++) {
string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
cout << "A () called" << endl;
}
~A () {
--count;
string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
cout << "~A () called" << endl;
}
A (const A &a) :indent (count++) {
string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
cout << "A (const A &) called" << endl;
}
const A &operator= (const A &a) {
string tem(indent, '\t'); cout<< tem << "[" << this << "] ";
cout << "A::operator= () called" << endl;
return *this;
}
};
int A::count = 0;
A g;
A fun()
{
A a;
return a;
}
int main(int argc, _TCHAR* argv[])
{
// Case 1: 返回值不用于赋值或初始化
{ cout << "---------------------------" << endl;
fun();
}
// Case 2: 返回值给变量赋值
{ cout << "---------------------------" << endl;
g = fun();
}
// Case 3: 返回值初始化
{ cout << "---------------------------" << endl;
A a = fun();
}
int in;
cin >> in;
return 0;
}
输出:
[0041B17C] A () called
---------------------------
[0012FE34] A () called
[0012FE70] A (const A &) called
[0012FE34] ~A () called
[0012FE70] ~A () called
---------------------------
[0012FE34] A () called
[0012FE7C] A (const A &) called
[0012FE34] ~A () called
[0041B17C] A::operator= () called
[0012FE7C] ~A () called
---------------------------
[0012FE34] A () called
[0012FF54] A (const A &) called
[0012FE34] ~A () called
[0012FF54] ~A () called
[0041B17C] ~A () called
注:以上输出是在VC8 Debug版本的输出,VC8 Debug版本的项目属性,默认配置时禁用优化(/Od)。
下面看一下Release版本的输出,Release版本项目属性,默认配置为(/O2)。
[00403378] A () called
---------------------------
[0012FF5C] A () called
[0012FF5C] ~A () called
---------------------------
[0012FF5C] A () called
[00403378] A::operator= () called
[0012FF5C] ~A () called
---------------------------
[0012FF60] A () called
[0012FF60] ~A () called
[00403378] ~A () called