【发布时间】:2018-09-25 06:05:38
【问题描述】:
我有一个名为 MyClass 的类,在调用构造函数或干扰器时会给出打印。 我正在尝试从 new 运算符分配内存。我对以下代码的输出有一些疑问。
<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 时,尽管分配了内存,但不会调用构造函数
- 根据new操作符如果分配了内存应该调用构造函数。
【问题讨论】:
-
如果你分配 0 个元素,那么构造函数应该有 0 次调用(显然)。您获得的内存不必包含已初始化的对象。
-
考虑使用
std::vector,而不是动态分配原始数组。它为您处理内存管理,并具有许多有用的功能。
标签: c++ arrays pointers memory new-operator