在阅读《C++ STL 中文版》时发现一段代码:
template<class T, class It> inline
T sum_all( It first, It last)
{
T sum;
for (sum = 0; first != last; ++first)
sum += *first;
return (sum);
}
这里返回了一个临时对象,我隐约记得,临时对象(一块内存)是不能被返回的,于是编写了以下测试程序testret.cpp:
#include <iostream>
using namespace std;
class A
{
string aStr;
public:
A(){cout << "Constructor of A." << endl;}
A(string str): aStr(str) {cout << "Constructor of A." << endl;}
~A(){cout << "destructor of A." << endl;}
void print(){cout << aStr << endl;}
};
A retA()
{
A a("hello");
a.print();
return (a);
}
int main()
{
A a = retA();
a.print();
return (0);
}
编译运行,输出入下:
Constructor of A.
hello
destructor of A.
hello
destructor of A.
在win32、HP-UX、solaris、AIX平台上运行结果一致。
这是为什么呢?可能是由于缺省拷贝构造函数引起的,于是在程序中增加一行:
A(const A &){cout << "Copy constructor of A." << endl;}
重载其缺省拷贝构造函数,该函数没有正确实现拷贝构造函数的功能,仅仅输出一行信息,此时编译运行,输出入下:
Constructor of A.
hello
Copy constructor of A.
destructor of A.
destructor of A.
注意输出中的空行。这表明,返回临时对象时,拷贝构造函数起了作用。拷贝构造函数使得可以像操作内建的数据类型一样操作用户数据类型。
当然,临时的对象集合依然无法返回,即:
class A;
……
A a[10];
此处a无法被返回。
Copyright (C) by raof01. 本文可以用于除商业用途外的所有用途。若要用于商业用途,请与作者联系。