gpt4 book ai didi

c++ - 如何解释 std::launder 的可达性要求?

转载 作者:行者123 更新时间:2023-12-03 02:28:50 27 4
gpt4 key购买 nike

std::launder 函数要求通过结果可访问的每个字节都可通过参数访问。 “可达”定义如下:

A byte of storage is reachable through a pointer value that points to an object Y if it is within the storage occupied by Y, an object that is pointer-interconvertible with Y, or the immediately-enclosing array object if Y is an array element.

根据an answer对于另一个问题,此限制“...意味着您不能使用 launder 来获取允许您访问比源指针值允许的更多字节的指针,因为存在未定义的行为。”

这对于 T.C. 给出的例子来说是有意义的。但我不明白在原始对象已被新对象替换的情况下如何解释它,这是 std::launder 预期的最初目的。该标准有以下示例:

struct X { const int n; };
X *p = new X{3};
const int a = p->n;
new (p) X{5}; // p does not point to new object (6.8) because X::n is const
const int b = p->n; // undefined behavior
const int c = std::launder(p)->n; // OK

在这种情况下,当std::launder被调用时,p指向的对象——原来的X对象——已经不复存在,因为在它所占用的存储中创建新对象已经隐式结束了它的生命周期([basic.life]/1.4)。因此,似乎没有可通过 p 访问的字节,因为 p 没有指向任何对象 Y。这显然不是预期的阅读方式,因为它会使示例中对 std::launder 的调用成为未定义的行为。

  1. 我是否误解了这里的措辞,或者措辞有缺陷?
  2. 使该示例有效的预期含义是什么?

最佳答案

仅以示例为例,相关文本是(粗体是我的):

A byte of storage is reachable through a pointer value that points to an object Y if it is within the storage occupied by Y

由于 placement new,指针值现在指向“新放置的”对象,因此可达性就是这样的。

我想说,就目前情况而言,这已经足够清楚了。

关于c++ - 如何解释 std::launder 的可达性要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465459/

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