gpt4 book ai didi

c++ - 我可以通过placement-new 覆盖const 对象吗?

转载 作者:行者123 更新时间:2023-12-04 11:43:24 25 4
gpt4 key购买 nike

Basic.life/8告诉我们,我们可以使用对象占用的存储空间在其生命周期结束后创建一个新对象,并使用其原始名称来引用它,除非:

  • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and [...]

强调我的
但是,就在其下方,我们可以看到一条说明:
  • If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std​::​launder

这说明 the purposes of std::launder .我们可以有一个具有 const 的类类型成员并使用placement-new 在那里创建一个具有不同内部值的新对象。
令我惊讶的是第一句话的第一部分。它清楚地表明如果存储是 const (不一定包含 const 成员,但整个对象被声明为 const ),我们不能用它来引用新对象,但它可能暗示 std::launder可能会修复它。
但是我们如何创建这样的对象呢?最简单的例子失败了:
const auto x = 5;
new (&x) auto(10);
这是因为我们不能使用 const void*作为放置新的缓冲区。我们可以 const_cast它,但抛弃了“真实” const ness 是未定义的行为。我相信这里也是如此。
如果只是禁止使用 const,我会理解对象作为放置新缓冲区,但如果是这样,第一个引用的强调部分的目的是什么?我们可以使用真正的重用 const不同对象的对象存储?

最佳答案

显然,只需要在我链接到的标准部分下方查看 2 个项目。 Basic.life/10告诉我们:

Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.


它带有一个例子:
struct B {
B();
~B();
};

const B b;

void h() {
b.~B();
new (const_cast<B*>(&b)) const B; // undefined behavior
}
这最终使我得出结论 使用展示位置是违法的- new关于被真正占用的内存const对象 .因此,我认为问题中提到的注释(引用点 8 )是错误的 - 它应该排除有问题的情况。

关于c++ - 我可以通过placement-new 覆盖const 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69276413/

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