可能是重复的问题:
如何使用new[]和delete导致内存泄漏?
delete与delete[]的区别
我刚开始学习C/C++,被告知要使用delete来删除单个对象,使用delete []来删除数组。
然后我发现了这个网站,它问了这个问题。
这就引出了一个问题,那么在这段代码块中到底会发生什么呢?我原本以为它会“只删除数组的第一个元素”,但似乎并不是这样。有人可以讲解一下吗?Anything wrong with this code?
T *p = new T[10]; delete p;
Note: Incorrect replies: “No, everything is correct”, “Only the first element of the array will be deleted”, “The entire array will be deleted, but only the first element destructor will be called”.
sizeof(size_t)
字符的指针,其中第一个元素被构造。这不适用于new
,因为不需要存储计数。delete
(与new
配对)只需调用析构函数并释放指针中的内存,而delete []
必须调用析构函数,并传递一个偏移了sizeof(size_t)
的指针以释放。 - David Rodríguez - dribeasmalloc
/free
),这是违反合约的行为。 - David Rodríguez - dribeas