Chinaunix首页 | 论坛 | 博客
  • 博客访问: 18106288
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类: C/C++

2008-05-31 08:38:39

以下函数ReturnObjectDirect与ReturnObject分别调用了多少次构造函数?
#include 
using namespace  std;

class Base
{
public:
    Base( )
    {
        cout<<\"缺省构造函数\"<    }
    Base(const Base & other)
    {
        cout<<\"复制构造函数\"<    }
    ~Base()
    {
        cout<<\"析造函数\"<    }
};

Base ReturnObjectDirect( )
{   
    return Base();
}

Base ReturnObject()
{   
    Base ret;
    return ret;
}

int main()
{
    Base obj1 =ReturnObjectDirect();
    Base obj2 =ReturnObject();
    
    return 0;

ReturnObjectDirect函数由于编译器优化所以只调用了一次缺省构造函数!

而ReturnObject函数
Base ret;                 //这里调用了一次缺省构造函数
return ret;          //调用拷贝构造函数将ret赋给临时变量
所以总共调用了二次构造函数!
阅读(364) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~