c++ - 在具有自动存储期限的 const 变量上放置 new 是否合法?

标签 c++ language-lawyer placement-new isocpp

根据标准,以下代码合法吗?

#include <new>
int main() {
    const int x = 3;
    new ((void *)&x) int { 15 };
}

在我看来,只要不使用 x 的引用即可它应该是有效的。

根据 C++ 标准 basic.life 8:

a pointer that pointed to the original object, a reference that referred to the original object [...]

  • 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

PS:如果答案可以包含对标准的引用,我们将不胜感激

最佳答案

Is the following code legal according to the standard?

程序的行为未定义:

[basic.life]

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.

关于c++ - 在具有自动存储期限的 const 变量上放置 new 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72226065/

相关文章:

c++ - 通过 argv[1] C++ 打开文件

c++ - 程序在 Visual Studio 2012 中运行,但不在 ideone.com 中运行

c++ - 为什么 C++17 中没有 std::construct_at ?

c++ - boost 几何 : composing polygons from many points

c++ - 如何摆脱堆栈溢出错误

c++ - Valgrind C++ : Invalid Read Of Size 8

java - 在 Java 中扩展私有(private)类

c++ - operator++ 作为后缀和前缀都不适用于 clang

c++ - 在 'this' 指针上使用 placement new 是否安全