woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

返回对象的效率

调用返回对象的函数时,调用函数负责在堆栈中分配对象大小的内存,并将对象指针传给被调用函数,被调用函数的

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;
}

posted on 2008-04-17 17:08 肥仔 阅读(217) 评论(0)  编辑 收藏 引用 所属分类: C++ 基础


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理