根据标准,以下代码合法吗?
#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/