C ++删除不带括号的数组内存仍然有效吗? [英] C++ delete array memory without brackets still works?

查看:88
本文介绍了C ++删除不带括号的数组内存仍然有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int* arr = new int[count];

delete arr;

为什么这样做?我已经检查过,它实际上释放了内存.根据我的阅读,我需要delete[] arr;,否则它实际上不会释放所有内存.

Why does this work? I've checked and it actually frees the memory. From what I've read I need delete[] arr; otherwise it won't actually free all the memory.

推荐答案

现在尝试用每个100字节的字符串填充数组,看看它是否仍释放所有分配的内存...

Now try it with filling the array with strings of 100 bytes each, and see if it still frees all the allocated memory...

这是不确定的行为,并且与往常一样,有时 UB似乎可以正常工作.在您的情况下,内存中没有对象的析构函数,因此没有进一步的工作",只需释放所有内存[1].但是,如果您的对象具有一个执行某些有用操作的析构函数,则该对象(可能)不会被调用.

It is undefined behaviour, and as always, sometimes UB will appear to work. In your case, you have no destructor for the objects in the memory, so there is no "further work", just free all the memory [1]. But if you have an object that has a destructor that does something useful, it (probably) won't get called.

如果使用new T[size];进行分配,则应始终使用delete [].请勿将两者混为一谈,这总是错误的-有时有时会起作用[就像毫米螺母上的某些英制扳手工作,反之亦然-但在公制螺母上使用英制扳手仍然是错误的].

You should ALWAYS use delete [] if you used new T[size]; to allocate. Don't mix the two, it's always wrong - just sometimes it HAPPENS to work [just like SOME sizes of spanners in inches works on mm nuts and vice versa - but it's still wrong to use a inches spanner set on metric nuts].

[1]请注意,这可能适用于此特定的编译器/C ++库组合.使用其他编译器,使用其他C ++库或针对其他OS进行编译可能会导致您在尝试相同操作时崩溃.

[1] Note that this may work for this particular compiler/C++ library combination. Compiling it with a different compiler, using a different C++ library, or compiling for a different OS may cause it to crash when you try the same thing.

这篇关于C ++删除不带括号的数组内存仍然有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆