如何正确删除指向数组的指针 [英] how to properly delete a pointer to array
问题描述
我是C ++的新手,我对数组和指针感到困惑。有人告诉我如何可以正确删除指针。例如,
I'm new to C++, and I'm confused about arrays and pointers. Could someone tell me how I can properly delete a pointer. Like for example,
int *foo;
foo = new int[10];
delete foo;
或
delete [] foo;
谢谢。
推荐答案
匹配new []和delete []的要求在技术上是正确的。
然而,更好的是,忘记你甚至听说过新的[],而不再使用它。我很确定自从上次使用新的[]以来已经(至少)10年了,如果我很好地理解这种情况,我会停止甚至更早。几乎任何时候,你甚至考虑使用新的[],std :: vector(或者可能std :: deque)将是一个更好的选择。
The requirement to match new[] with delete[] is technically correct.
Much better, however, would be to forget that you ever even heard of new[], and never use it again. I'm pretty sure it's been (at least) 10 years since the last time I used new[], and if I'd understood the situation very well, I'd have stopped even sooner than that. Pretty nearly any time you'd even consider using new[], an std::vector (or possibly std::deque) will be a better choice.
这篇关于如何正确删除指向数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!