本文介绍了指针算术在分配的存储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]

[expr.add]

我的解释是,分配提供了一个可能假想的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上吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 01:19