2

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

Jason
  • 36,170
  • 5
  • 26
  • 60
Dorian
  • 490
  • 2
  • 10
  • could just as well use `const_cast`. And like it says on [cppreference](https://en.cppreference.com/w/cpp/language/const_cast): _"Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior. "_ – JHBonarius May 13 '22 at 07:47
  • That is what I thought, so legal ? – Dorian May 13 '22 at 07:49
  • 1
    `const` objects can reside in non-writable memory areas resulting in a segmentation fault (had a similar case on porting an application from vxWorks 6.4 to 7.0 – at the former original code got away with modifying string literals (UB), on the latter crash...). Apart from not being legal that might have serious consequences! – Aconcagua May 13 '22 at 07:53
  • @Dorian How could it be legal? According to the first comment, even the modification itself causes undefined behavior. – Daniel Langr May 13 '22 at 08:01
  • @DanielLangr It's not so clear. Dorian is creating a new object. In case of trivial objects, this implicitly destroys the old object. Destruction is not modification in the sense that wouldn't be allowed for const. It's another rule that explicitly disallows this. – eerorika May 13 '22 at 08:10
  • @eerorika You're right, thanks for pointing this out. Your answer explains that well. – Daniel Langr May 13 '22 at 08:16
  • UB for the const as answer indicates. Also, there is no way to locate a reference unless it is a subobject so it's not even syntactically doable. – doug May 13 '22 at 14:40

1 Answers1

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326