我可以删除[]'一个指针指向一个分配的数组,但不是开始吗? [英] Can I 'delete[]' a pointer that points into an allocated array, but not to the start of it?

查看:124
本文介绍了我可以删除[]'一个指针指向一个分配的数组,但不是开始吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我特别想知道下面的情况(我发现在一些代码中我必须使用):

  SomeClass * ar = new SomeClass [2]; 
ar ++;
delete [] ar;

这段代码似乎工作正常 - 即不崩溃(win32,用VS2005构建) p>

这是合法吗?

$ p

解决方案

否,它未定义为将任何地址传递给 delete c $ 这是标准的报价。



§3.7.4.2-3



如果解除分配函数通过抛出异常终止,未定义。提供给解除分配函数的第一自变量的值可以是空指针值;如果是,并且如果解除分配函数是在标准库中提供的,则调用没有效果。否则,在标准库中向操作符 delete(void *)提供
的值应为以前调用操作符 new(std :: size_t)运算符new(std :: size_t,const std :: nothrow_-t&)标准库中,并且提供给标准库中的操作符 delete [](void *)的值应为之前调用 operator new [](std :: size_t)
c $ c>在标准库中。


I'm wondering specifically about the following situation (which I discovered in some code I have to work with):

SomeClass *ar = new SomeClass[2];
ar++;
delete[] ar;

This code seems to be working fine - i.e. not crashing (win32, built with VS2005).

Is this "legal"? It certainly doesn't feel right.

解决方案

No, it is undefined to pass any address to delete which was not returned by new.
Here is the quote from the Standard.

§ 3.7.4.2-3

If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_-t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

这篇关于我可以删除[]'一个指针指向一个分配的数组,但不是开始吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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