cplusplus / CWG

Core Working Group
23 stars 7 forks source link

[basic.life] Creating object within a mutable member subobject of a const complete object #367

Open frederick-vs-ja opened 1 year ago

frederick-vs-ja commented 1 year ago

Full name of submitter (unless configured in github; will be published with the issue): Jiang An

Reference (section label): [basic.life]

Link to reflector thread (if any):

Issue description:

Per [basic.life] p10, the following program has undefined behavior.

int main() {
  struct S {
    alignas(int) mutable unsigned char buf[sizeof(int)];
  };
  const S s{};
  ::new ((void*)s.buf) int{42};
}

Disallowing creating objects within a mutable member looks like an oversight, since it seemingly defeats the purpose of mutable.

We should also determine whether the behavior is well-defined if a union type has both mutable and non-mutable non-static data members, and an object is created within the mutable member of such a const complete union object.

Implementations accept the following code (Godbolt link), although it includes UB (per current rules) in constant evaluation.

constexpr bool test1() {
  union U {
    int x;
    mutable float y;
  };
  constexpr U u{.x = 42};
  u.y = 42.0f;
  return true;
}
static_assert(test1());

Suggested resolution: