Skip to content

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

Description

@frederick-vs-ja

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] p12, 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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions