Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1700209
  • 博文数量: 177
  • 博客积分: 9416
  • 博客等级: 中将
  • 技术积分: 2513
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-06 16:08
文章分类

全部博文(177)

文章存档

2013年(4)

2012年(13)

2011年(9)

2010年(71)

2009年(12)

2008年(11)

2007年(32)

2006年(25)

分类: C/C++

2006-02-23 09:10:00

在阅读《C++ STL 中文版》时发现一段代码:
template inline
T sum_all( It first, It last)
{
    T sum;
    for (sum = 0; first != last; ++first)
        sum += *first;
    return (sum);
}
这里返回了一个临时对象,我隐约记得,临时对象(一块内存)是不能被返回的,于是编写了以下测试程序testret.cpp:
#include
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无法被返回。
 
Copyleft (C) 2007-2009 raof01.
本文可以用于除商业外的所有用途。此处“用途”包括(但不限于)拷贝/翻译(部分或全部),不包括根据本文描述来产生代码及思想。若用于非商业,请保留此 权利声明,并标明文章原始地址和作者信息;若要用于商业,请与作者联系(raof01@gmail.com),否则作者将使用法律来保证权利。
阅读(3229) | 评论(6) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-09-29 22:37:15

汗楼上的。。。

chinaunix网友2008-05-06 14:15:43

看文章還不如看注釋, 受教