您的位置:首页 > 编程语言 > C语言/C++

c++的拷贝构造函数的思考(当返回对象时,发生什么)

2012-04-18 17:16 302 查看
当函数返回对象时(return a),会调用拷贝构造函数生成一个对象给外部用,同时退出时把内部对象析构

#include "stdafx.h"

#include <iostream>

using namespace std;

static int i;

class A{

public:

A(){

cout<<"constructor i="<<++i<<endl; //(1) 步 constructor i=1

}

A(A &a){

cout<<"copy constructor i="<<++i<<endl; //(3)步 copy constructor i=2

cout<<"in copy a="<<&a<<endl; //(4) 步 in copy a=0012FF04

cout<<"in copy this="<<this<<endl; //(5)步in copy this=0012FF70

}

~A(){

cout<<"destructor"<<--i<<endl; //(6)步,destructor1

}

};

A get(){

A a;

cout<<&a<<endl; //(2) 步 0012FF04

return a; //在return a 前发生了3,4,5步,然后析构局部变量a

}

int main(int argc, char* argv[])

{

A a=get();

cout<<&a<<endl; //(7)步,0012FF70
发现和四部的this指针一样,即这个a就是在get()内部调用拷贝构造函数生成的对象,其实是吧这里a 的地址传给了get()

return 0; //(8) 步,destructor0 析构a

}

Press any key to continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: