指针算术在分配的存储UB上吗? [英] Is pointer arithmetic on allocated storage UB?

查看:54
本文介绍了指针算术在分配的存储UB上吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要实现std :: vector而不调用任何未定义行为(UB).下面的代码是否调用UB:

Let's say I want to implement std::vector without invoking any undefined behavior (UB). Is the code below invokes UB:

struct X{int i;};
int main(){
  auto p = static_cast<X*>(::operator new(sizeof(X)*2));
  new(p) X{};
  new(p+1) X{};// p+1 UB?
}

在标准中选择一些可能有帮助的报价:

Folowing a selection of quote from the standard that may help:

[basic.stc.dynamic.allocation]

(由分配函数返回的)指针应适当对齐,以便可以将其转换为指向任何指针的指针. 合适的完整对象类型(21.6.2.1),然后用于访问分配的存储中的对象或数组 (直到通过调用相应的释放函数显式释放存储空间为止).

The pointer returned (by an allocation function) shall be suitably aligned so that it can be converted to a pointer to any suitable complete object type (21.6.2.1) and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call to a corresponding deallocation function).

[expr.add]

当将具有整数类型的表达式添加到指针或从指针中减去时,结果具有该类型 指针操作数的值.如果表达式P指向具有n个元素的数组对象x的元素x [i], 表达式P + J和J + P(其中J的值为j)指向(可能是假设的)元素 如果0 <= i + j <= n,则x [i + j];否则,行为是不确定的.同样,表达式P-J指向 如果0 <= i − j< = n,则(可能是假设的)元素x [i-j];否则,行为是不确定的.

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression P points to element x[i] of an array object x with n elements, the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i + j] if 0<=i + j<=n; otherwise, the behavior is undefined. Likewise, the expression P - J points to the (possibly-hypothetical) element x[i − j] if 0<=i − j <=n; otherwise, the behavior is undefined.

我的解释是,分配提供了一个可能假想的X数组(在C ++数组中是对象),因此在分配的存储中进行指针算术运算(例如在示例中)可能不会调用不确定的行为.还是我对假设的解释是错误的?如果先前的代码片段是UB,该怎么办?

My interpretation is that allocation provides an possibly-hypothetical array of X (in C++ arrays are objects) so pointer arithmetic on allocated storage as in the exemple may not invoke undefined behavior. Or my interpretation of hypothetical is wrong? How could I do if the previous code snipest is UB?

推荐答案

是的,从技术上讲,它具有不确定的行为,尽管我们倾向于忽略它. P0593 应该正确修复.

Yes, technically it has undefined behaviour, though we tend to ignore that. P0593 should fix it properly.

可能是假设的"一词指的是单端的元素"( ref ),并且不允许这种情况.

The phrase "possibly-hypothetical" refers to one-past-the-end "elements" (ref), and does not permit this case.

这篇关于指针算术在分配的存储UB上吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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