C++ 申請連續的對象記憶體

來源:互聯網
上載者:User

實在慚愧,想要申請指向一個類的連續的批量的記憶體,盡然不知道怎麼申請……

1 基本類型的申請

   //申請連續的10個指向int類型記憶體
int *pArray = new int(10);

 

2 結構體和類

class A
{
public:
A(int a){}
private:
int x;
};

//申請10個連續的指向A對象的記憶體
pA = new A[10]; //error 無預設建構函式
pA = new A[10](0); //error 不支援

 

class A
{
public:
A(){}
A(int a){}
private:
int x;
};

A *objA = (A*) operator new (sizeof(A)*10); //不調用建構函式
for (int i = 0; i < 10 ; i++)
{
new (objA + i) A(0); //調用相應建構函式 初始化 不分配記憶體
}

 

具體用法可以查詢operator new的用法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.