首页 > 代码库 > Effective C++ 笔记
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; }
Effective C++ 笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。