簡體   English   中英

在對象數組中,構造函數被多次調用但是operatror new []只調用一次,為什么?

[英]In the array of objects, constructor is called many times but operatror new[] only once , why?

當在堆中創建對象時,它(新)做兩件事。

1:調用operator new

2:調用構造函數初始化obejct。

我正在嘗試創建對象數組,例如4個對象,所以它調用構造函數和析構函數4次才有意義,但它只調用一次運算符new [] ?? 為什么? 以下是我試圖運行的代碼。

#include <iostream>
using namespace std;
class test
{
    public:
       static void *operator new[] (size_t size)
       {
           cout<<"operaotor new called"<<endl;
           return ::operator new[](size);
       }

       test()
       {
          cout<<"constructor called"<<endl;
       }
       ~test()
       {
          cout<<"destructor called"<<endl;
       }
};

int main()
{

     test *k = new test[4];
     delete []k;
}

operator new[] 用於分配必要的空間,沒有別的。 當然,它只會這樣做一次,因為其他任何東西都是無關的,並且不會得到連續的緩沖區。 new test[4]的情況下,你得到的size參數應該是4 * sizeof(test)

對於數組中的每個項,構造函數和析構函數都被調用一次,而new []只被調用一次,因為您只創建了一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM