数组大小为零时的C ++内存分配行为

时间:2018-04-15 11:29:01

标签: c++ arrays pointers memory new-operator

我有一个名为MyClass的类,在调用构造函数或distractor时给出了一个print。 我正在尝试从新运算符分配内存。我对下面代码的输出有一些疑问。

<code>
#include...
class MyClass
{
    public:
    MyClass()
    {
        cout << "MyClass Object Created \n";
    }

    ~MyClass()
    {
        cout << "MyClass Object Deleted\n+";
    }
};
int main(int argc, const char * argv[])
{
  int size = 0; // if the size is zero
  std::cout << "Hello, World!\n";
  MyClass *mclass = NULL;
  cout << "before allocating the memory :" <<  mclass << endl;
  mclass = new MyClass[size](); //object will not be constructed.
  cout << "after allocating the memory :"<<  mclass << endl;
  delete [] mclass;
  cout << "after deallocating the memory :"<<  mclass << endl;
  return 0;
}
</code>

问题 - 1.如果数组大小为1,2,...调用任何int值构造函数但是当数组大小为0时,虽然已分配内存,但不会调用构造函数

  1. 根据new运算符,如果内存被分配,则应该调用构造函数。

1 个答案:

答案 0 :(得分:2)

数组大小为零时,没有要构造的数组项。

就这么简单。

你得到一个唯一的地址,这意味着至少有一个字节被分配,必须像往常一样被释放。