大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
class Object
{
public:
    Object() 
{cout<<"Default"<<endl;}
    Object(
const Object&{cout<<"Copy"<<endl;}
    Object
& operator =(const Object&{cout<<"Assignment"<<endl; return *this;}
    
~Object() {cout<<"Destructor"<<endl;}
}
;

    Object def;                    //default
    Object def2((Object()));    //default,optimization
    Object def3 = Object();        //default,optimization
    Object cop(def);            //copy
    Object cop2 = def;            //copy
    cop2 = def;                    //assignment
输出:
Default
Default
Default
Copy
Copy
Assignment

void TestPara(const Object obj)
{
    
//call copy constructor
}


void TestParaRef(const Object& obj)
{
    
//call no constructor
}

当返回引用时如下调用,先调用默认构造函数,再调用拷贝构造函数,返回局部变量的引用时禁止的。
Object& TestReturnRef()
{
    Object obj;
    
return Object();        //the same with return Object(); return local variable, forbidden!
}

   Object o = TestReturnRef();   

   

返回值:
Object TestReturn()
{
    Object obj;
    
return obj;
}


    Object opt 
= TestReturn();    //1 default, optimization

    Object obj;                    
//2 default, 1 assignment
    obj = TestReturn();

Object TestReturn()
{
    Object obj;
    
return obj;
}

//in release version, 1 default called
//in debug version, 1 default, 1 copy

Object TestReturn()
{
    
return Object();
}

//in release version, 1 default called
//in debug version, 1 default called

类类型变量初始化使用=时调用copy constructor, 如上两个优化的情况例外。
对已构造的对象使用=时调用赋值操作符。
posted on 2009-05-25 16:12 大胖 阅读(112) 评论(0)  编辑 收藏 引用 所属分类: C++

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