Effective C++ 笔记
无参构造函数如何暴躁的构造.
先来看看标准的raw_memory :
void *intRawVar = operator new[](5*sizeof(int)); // create int raw memory int *intVars = static_cast<int *>(intRawVar); // let int object to point this raw memory for(int i=0;i<5;i++) { new(&intVars[i])int(i*10); } for(int i=0;i<5;i++) { cout << intVars[i] <<endl; } operator delete[](intRawVar);
无参数如何暴力构造
#include <iostream> class EquipmentPiece { public: EquipmentPiece(int IDNumber){ _var = IDNumber; } ~EquipmentPiece() { } private: int _var; }; using namespace std; int main(int argc, char *argv[]) { //<1> //EquipmentPiece piece[10]; //error not default constructor //<2> typedef EquipmentPiece* PEP; //this method is ok,have resource leak & big memory allocation PEP piece[10]; // create ten EquipmentPiece* pointer //PEP *piece = new PEP[10]; // always is ok for(int i=0;i<10;i++) { piece[i] = new EquipmentPiece(i); } for(int i=0;i<10;i++) { delete piece[i]; } void *rawMemory = operator new[](10*sizeof(EquipmentPiece)); EquipmentPiece *pieces = static_cast<EquipmentPiece*>(rawMemory); for(int i=0;i<10;i++) { new(&pieces[i])EquipmentPiece(i); } // release the EquipmentPiece object with reverse direction for(int i=9;i >=0;--i) { pieces[i].~EquipmentPiece(); } // release the raw memory operator delete[](rawMemory); return 0; }