调用返回对象的函数时,调用函数负责在堆栈中分配对象大小的内存,并将对象指针传给被调用函数,被调用函数的
return语句调用该对象的构造函数或拷贝构造函数来初始化该对象.以下程序是一个例子.特别注意在没有定义
EFFECTIVE的情况下程序的效率下降.
#include <stdio.h>
#define EFFECTIVE
class CBase
{
public:
CBase(int i){
m_iValue = i;
printf("CBase(int i)\n");
}
CBase()
{
m_iValue = 0;
printf("CBase()\n");
}
CBase(const CBase & base)
{
printf("CBase(const Base &base)\n");
m_iValue = base.m_iValue;
}
operator = (const CBase &base)
{
printf("operator =\n");
this->m_iValue = base.m_iValue;
}
~CBase(){
printf("~Base()\n");
}
public:
int m_iValue;
int m_iValue2;
};
CBase test()
{
#ifdef EFFICTIVE
return CBase(100);
#else
CBase base(100);
return base;
#endif
}
int main()
{
#ifdef EFFICTIVE
CBase base = test();
#else
CBase base;
base = test();
#endif
return 0;
}