在对象数组中,构造函数被多次调用但是operatror new []只调用一次,为什么?

Alo*_*lok 3 c++

当在堆中创建对象时,它(新)做两件事.

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;
}
Run Code Online (Sandbox Code Playgroud)

Xeo*_*Xeo 6

operator new[]唯一有分配必要的空间,没有别的.当然,它只会这样做一次,因为其他任何东西都是无关的,并且不会得到连续的缓冲区.size在这种情况下new test[4],你得到的参数应该是4 * sizeof(test).