码迷,mamicode.com
首页 > 编程语言 > 详细

Effective C++ 笔记

时间:2017-02-13 23:54:49      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:reverse   std   har   tpi   public   UI   log   eof   err   

无参构造函数如何暴躁的构造.

先来看看标准的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++ 笔记

标签:reverse   std   har   tpi   public   UI   log   eof   err   

原文地址:http://www.cnblogs.com/gearslogy/p/6395806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!