gpt4 book ai didi

c++ - 对已删除的数组进行指针运算仍然合法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:17 25 4
gpt4 key购买 nike

今天我写了一些看起来像这样的东西:

void foo(std::vector<char>&v){
v.push_back('a');
char*front=&v.front();
char*back=&v.back();
size_t n1=back-front+1;
v.push_back('b');//This could reallocate the vector elements
size_t n2=back-front+1;//Is this line valid or Undefined Behavior ?
}

如果在我将“b”推回时发生重新分配,我是否仍可以计算我的两个指针的差异?

看了几次标准的相关段落,我还是拿不定主意。

C++11 5.7.6:当两个指向同一个数组对象的元素的指针相减时,结果是两个数组元素的下标。结果的类型是一个实现定义的有符号整数类型;此类型应与 header (18.2) 中定义为 std::ptrdiff_t 的类型相同。作为对于任何其他算术溢出,如果结果不适合提供的空间,则行为未定义。换句话说,如果表达式 P 和 Q 分别指向数组对象的第 i 个和第 j 个元素,表达式 (P)-(Q) 具有值 i − j,前提是该值适合 std::ptrdiff_t 类型的对象。此外,如果表达式 P 指向数组对象的元素或指向数组对象最后一个元素的元素一个数组对象,表达式 Q 指向同一个数组对象的最后一个元素,表达式((Q)+1)-(P) 与 ((Q)-(P))+1 和 -((P)-((Q)+1)) 具有相同的值,并且具有零值如果这表达式 P 指向数组对象的最后一个元素,即使表达式 (Q)+1 没有指向数组对象的一个​​元素。 除非两个指针都指向同一个数组对象的元素,或者数组对象的最后一个元素之后,行为未定义。

我当然知道它有效,我只是想知道它是否合法。

最佳答案

指向已删除对象的指针是有毒的:除了给它们一个新值外,不要触摸它们。内存跟踪系统可能会通过使用回收的指针值来陷入困境。不过,我不知道是否存在这样的系统。

相关引用是 3.7.4.2 [basic.stc.dynamic.deallocation] 第 4 段:

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value, the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.

调整 std::vector<...> 大小时它会跳过许多环(分配器),默认情况下,最终会调用释放函数。

关于c++ - 对已删除的数组进行指针运算仍然合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20569852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com