我特别想知道以下情况(我在一些代码中发现了我必须使用的情况):
SomeClass *ar = new SomeClass[2];
ar++;
delete[] ar;
Run Code Online (Sandbox Code Playgroud)
这段代码似乎运行正常 - 即没有崩溃(win32,使用VS2005构建).
这是"合法的"吗?当然感觉不对.
Alo*_*ave 21
不,未定义传递任何delete未返回的地址new.
以下是标准的引用.
§3.7.4.2-3
如果通过抛出异常终止释放函数,则行为未定义.提供给解除分配函数的第一个参数的值可以是空指针值; 如果是这样,并且如果解除分配功能是标准库中提供的功能,则该调用无效.否则,delete(void*)在标准库中提供给操作符的值应该是先前调用任何操作符new(std::size_t)或operator new(std::size_t, const std::nothrow_-t&)在标准库中返回的值之一,并且提供给delete[](void*)标准库中的操作符的值应该是由a返回的值之一.以前调用任何一个operator new[](std::size_t)或
operator new[](std::size_t, const std::nothrow_t&)在标准库中.
不它不是.您必须在从新[]收到的相同地址(或指针)上调用delete [].你可能只是幸运的是它没有崩溃,但它绝对不能恰当地清除内存.
参考文献:
来自http://www.cplusplus.com/doc/tutorial/dynamic/
The value passed as argument to delete must be either a pointer to a memory block
previously allocated with new, or a null pointer (in the case of a null pointer,
delete produces no effect).
Run Code Online (Sandbox Code Playgroud)
来自http://msdn.microsoft.com/en-us/library/h6227113.aspx
Using delete on a pointer to an object not allocated with new gives
unpredictable results. You can, however, use delete on a pointer with the
value 0. This provision means that, when new returns 0 on failure, deleting
the result of a failed new operation is harmless.
Run Code Online (Sandbox Code Playgroud)
来自标准文档.5.3.5.2Delete,
...在第二个备选(删除数组)中,delete的操作数的值应该是由前一个数组new-expression产生的指针值.72)如果不是,则行为是未定义的.....
分注72)还指出,
72)对于非零长度数组,这与指向该new-expression创建的数组的第一个元素的指针相同.零长度数组没有第一个元素.
所以是的,它是未定义的.
| 归档时间: |
|
| 查看次数: |
1786 次 |
| 最近记录: |