調用返回對象的函數時,調用函數負責在堆棧中分配對象大小的內存,并將對象指針傳給被調用函數,被調用函數的
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;
}