构造、析构函数的调用顺序及VC6.0和VC2010中实现的差别

构造、析构函数的调用顺序及VC6.0和VC2010中实现的差别

 

VC6.0和VC2010在初始化数组的时候存在差别:对于

vector<Item_base> ibvec( 3 );


在6.0中这条语句是先利用默认构造函数创建一个临时对象,然后三次调用复制构造函数,将此临时对象赋给数组中的值,再调用析构函数撤销临时对象;

在2010中,这条句是先利用默认构造函数创建一个临时对象,然后调用复制构造函数将此临时对象赋给数组中的一个值, 再调用析构函数撤销临时对象;再反复这个过程初始化数组的另外两个值。

详细代码如下:

#include <iostream>
#include <vector>
using namespace std;

class Item_base
{
public:
	Item_base()
	{
		cout << "Item_base()" << endl;
	}
	Item_base( const Item_base& )
	{
		cout << "Item_base( const Item_base& )" << endl;
	}
	Item_base& operator = ( const Item_base &rhe )
	{
		cout << "operator = ( const Item_base& )" << endl;
		return *this;
	}
	~Item_base()
	{
		cout << "~Item_base()" << endl;
	}
};

void func1( Item_base obj )
{
}

void func2( Item_base &obj )
{
}

Item_base func3()
{
	Item_base obj;
	return obj;
}


int main()
{
	Item_base ib;
	func1( ib );
	func2( ib );
	ib = func3();
	Item_base *p = new Item_base;
	vector<Item_base> ibvec( 3 );
	delete p;
	
	return 0;
}

 

VC6.0中的运行结果:


Item_base()
Item_base( const Item_base& )
~Item_base()
Item_base()
Item_base( const Item_base& )
~Item_base()
operator = ( const Item_base& )
~Item_base()
Item_base()
Item_base()
Item_base( const Item_base& )
Item_base( const Item_base& )
Item_base( const Item_base& )
~Item_base()
~Item_base()
~Item_base()
~Item_base()
~Item_base()
~Item_base()


 

VC2010中的运行结果:

Item_base()
Item_base( const Item_base& )
~Item_base()
Item_base()
Item_base( const Item_base& )
~Item_base()
operator = ( const Item_base& )
~Item_base()
Item_base()
Item_base()
Item_base( const Item_base& )
~Item_base()
Item_base()
Item_base( const Item_base& )
~Item_base()
Item_base()
Item_base( const Item_base& )
~Item_base()
~Item_base()
~Item_base()
~Item_base()
~Item_base()
~Item_base()


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值