'Is placement new on a const variable with automatic storage duration legal? [duplicate]

Is the following code legal according to the standard?

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

It seems to me that as long as there is no use of a reference to x it should be valid.

As per the c++ standard 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 : if the answer could contain a reference to the standard it would be much appreciated



Solution 1:[1]

Is the following code legal according to the standard?

The behaviour of the program is undefined:

[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eerorika