删除对象数组方式的区别
以下对象数组的删除有什么不同吗?
第一种方式:
MyClass **obj = new MyClass*[NUM];
for (int i=0; i<NUM; i++) obj[i] = new MyClass(val);
obj[0]->method();
for (int i=0; i<NUM; i++) delete obj[i]; /// Deletion1
delete obj; /// Deletion1
第二种方式:
MyClass **obj = new MyClass*[NUM];
for (int i=0; i<NUM; i++) obj[i] = new MyClass(val);
obj[0]->method();
delete[] obj; /// Deletion2
obj = 0x0; /// Deletion2
两种方式都是可行的,并且在调试器中看起来相似。
Is there some difference in the following deletions of object array?
The first way:
MyClass **obj = new MyClass*[NUM];
for (int i=0; i<NUM; i++) obj[i] = new MyClass(val);
obj[0]->method();
for (int i=0; i<NUM; i++) delete obj[i]; /// Deletion1
delete obj; /// Deletion1
The second way:
MyClass **obj = new MyClass*[NUM];
for (int i=0; i<NUM; i++) obj[i] = new MyClass(val);
obj[0]->method();
delete[] obj; /// Deletion2
obj = 0x0; /// Deletion2
Both ways are workable and look similar in debugger.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两者都不正确。正确的方法是:
在您展示的第一种方式中,您使用
delete
来销毁使用new[]
分配的对象,这会导致未定义的行为(如果您使用 < code>new[],则必须使用delete[]
销毁该对象)。在您展示的第二种方式中,您泄漏了在第一个 for 循环中创建的所有指针。
如果您使用 std::vector 而不是动态分配的数组和某种类型的智能指针,那么在大多数代码中您不必担心这一点。
Both are incorrect. The correct way would be:
In the first way you show, you use
delete
to destroy an object allocated withnew[]
, which results in undefined behavior (if you usenew[]
, you must destroy the object usingdelete[]
).In the second way you show, you leak all of the pointers that you created in the first for loop.
If you use
std::vector
instead of dynamically allocated arrays and some type of smart pointer, then you don't have to worry about this in most code.在第一个示例中,您为分配的数组的成员所指向的每个对象显式调用析构函数。然后,您将删除指针数组(实际上应该是
delete[]
,因为您将其分配为数组,但实际上对于本示例而言,它可能并不重要)。在第二个示例中,您仅删除指针数组,它不会调用指向对象的析构函数。之所以没有这样做,是因为您可能已经在编译器不一定知道的其他变量中复制了这些指针。
如果您要创建一个对象数组,而不是指针,如下所示:
那么
delete[]
运算符将自动为每个对象调用析构函数已分配数组中的NUM
个对象。In your first example, you are explicitly calling the destructor for each object pointed to by members of the allocated array. Then you are deleting the array of pointers (which should really be
delete[]
because you allocated it as an array, but in practice for this example it probably doesn't matter).In your second example, you are only deleting the array of pointers, which does not call the destructor for the pointed-to objects. The reason it doesn't is that you may have made copies of those pointers in other variables which the compiler doesn't necessarily know about.
If you were to create an array of objects and not pointers, like this:
then the
delete[]
operator would automatically call the destructor for each of theNUM
objects in the allocated array.