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

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

问题描述

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

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;

此代码似乎运行良好-即不会崩溃(win32,使用VS2005构建)。

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

这是合法吗?肯定感觉不对。

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

推荐答案

否,未定义将任何地址传递给 delete ,不是 new 返回的。

这是标准中的报价。

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

如果释放函数因抛出异常而终止,则该行为未定义。提供给解除分配函数的第一个参数的值可以是空指针值。如果是这样,并且如果释放函数是标准库中提供的函数,则该调用无效。否则,向标准库中的运算符 delete(void *)提供的
值应为先前调用任一运算符<$ c返回的值之一。 $ c> new(std :: size_t)或 operator new(std :: size_t,const std :: nothrow_-t&)标准库,并且在标准库中提供给运算符 delete [](void *)的值应为先前调用<$ c $返回的值之一c> operator new [](std :: size_t)或
operator new [](std :: size_t,const std :: nothrow_t&)在标准库中。

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天全站免登陆