类对象数组初始化

时间:2021-03-20 19:42:34

如有一个如下类:

class EquipmentPiece { private: int IDNumber; public: EquipmentPiece(int IDNumber) : IDNumber(IDNumber) {}; };

 

以下列出几种初始化的方法:

<一>、对象数组

int ID1, ID2, ID3; EquipmentPiece bestPieces[] = { EquipmentPiece(ID1), EquipmentPiece(ID2), EquipmentPiece(ID3) };

注意:

EquipmentPiece bestPieces[10]; //no appropriate default constructor available EquipmentPiece *bestPieces = new EquipmentPiece[10]; //no appropriate default constructor available

当然,如果你将构造函数参数全都设了默认值,以上两种写法也成功,如将类中构造函数修改如下: ... EquipmentPiece(int IDNumber = 0) : IDNumber(IDNumber) {}; ...

 

<二>、指针数组

typedef EquipmentPiece* PEP; //PEP是个指向EquipmentPiece的指针

PEP bestPieces[10]; //等同于 PEP *bestPieces = new PEP[10];

//然后初始化 for(int i = 0; i < 10; i++){ bestPieces[i] = new EquipmentPiece( IDNumber ); }

注意: 要记得将此数组所指的所有对象删除。如果忘了会产生资源泄露。还有就是该方法与对象数组相比需要额外内存用于存放指针。(过度使用内存 这一问题可以避免,见第三种方法)

 

<三>、使用placement new(定位new操作符)

方法是:先为此数组分配raw memory,然后使用"placement new"在这块内存上构造EquipmentPiece objects;

 

//分配足够的raw memory,给一个预备容纳10个EquipmentPiece objects的数组使用 void *rawMemory = operator new(10*sizeof(EquipmentPiece));

//让bestPieces指向此内存,使这块内存被视为一个EquipmentPiece数组 EquipmentPiece *bestPieces = reinterpret_cast<EquipmentPiece*>(rawMemory);

//利用"placement new"构造这块内存中的EquipmentPiece objects。 int IDNumber = 0; for(int i = 0; i < 10; i++){ new (&bestPieces[i]) EquipmentPiece( IDNumber ); }

 

注意:该方法维护比较困难。在数组内对象结束生命时,要以手动方式调用destructors,最后还得调用operator delete释放raw memory。

//将bestPieces中对象以构造次序的反序析构掉 for(i = 0; i < 10; i++){ bestPieces[i].~EquipmentPiece(); }

//释放raw memory operator delete (rawMemory);