在具有自动存储持续时间的 const 变量上放置 new 是否合法?
Is placement new on a const variable with automatic storage duration legal?
根据标准,以下代码是否合法?
#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.
根据标准,以下代码是否合法?
#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.