带参构造函数的类对象数组初始化

今天同学问我个问题:有一个带参构造函数的类,如何初始化其对象数组?仔细想了想,应该不难额,比如:

#include <iostream>  
using namespace  std;  

class A {
public:
	A(int a)
	{cout << "construct" << a << endl;}
};

int main()  
{  
	A arr[] = {A(1), A(2), A(3), A(4), A(5)};
	return 0;  
}  
但是问题来了,如果数组长度太大怎么办?想了一下,目前所知道的有两种比较好的办法:

(1)使用STL容器vector来代替静态数组:

#include <iostream> 
#include <vector> 

class A {
public:
	A(int a)
	{cout << "construct" << a << endl;}
};

int main()  
{  
	vector<A> va;
	for(int i = 0; i < 50; i++)
		va.push_back(A(i));
	return 0;  
}  
但这里每次push_back时除了调用A的构造函数外还会调用A的拷贝构造函数,而且在数组大小动态增长的过程中,由于动态申请内存可能导致数据的搬移也会再次调用A的拷贝构造函数,这样效率比较低下。

(2)利用operator new + 动态内存处理:

#include <iostream> 
using namespace  std;  

class A {
public:
	A(int a)
	{cout << "construct" << a << endl;}
	~A()
	{cout << "~A()\n";}
};

int main()  
{  
	A *pa = reinterpret_cast<A *>(::operator new(sizeof(A) * 50));
	for(int i = 0; i < 50; i++)
		new(&pa[i]) A(i);
	for(int i = 0; i < 50; i++)
		pa[i].~A();
	delete pa;
	return 0;  
}  
不过,这里要注意自行调用A的析构函数,而且这里申请的内存虽然用于数组,但operator new仅申请内存,并未存放数组长度等信息,不能由delete []的形式释放。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值