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
#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
相关文章推荐
- C++13.1.2合成复制构造函数----定义复制对象时会发生什么
- C++ 13.2 类赋值操作符----定义该类型对象赋值时会发生什么(有不懂)
- c++怎样让返回对象的函数不调用拷贝构造函数
- c++怎样让返回对象的函数不调用拷贝构造函数
- 关于C++中在函数中按值返回、临时对象、拷贝构造函数的一点理解
- C++ 函数返回对象时并没有调用拷贝构造函数
- C++ 对象间的赋值与拷贝构造函数
- C++中 简单查看临时对象,局部对象的生命周期,及拷贝构造函数(测试代码)
- 【翠字营原创】: C++ 临时对象分析小结 涉及函数参数值传递、函数返回值、仿函数
- 关于C++函数返回局部对象的详细分析
- C++对象模型之默认构造函数的构造操作,拷贝构造函数同
- 如果autorelease NSAutoreleasePool对象会发生什么?
- C++箴言:必须返回对象时别返回引用
- C++中的临时对象(拷贝构造函数)(上)
- JS new对象内部发生了什么
- 继承关系下new子类对象,会发生什么?
- C++:笔记:什么是对象
- C++ 什么是对象
- C++中定义对象的语法,带括号与不带括号有什么区别?
- 【C++对象模型】函数返回C++对象的问题