cplusplus / cplusplus/draft

the lifetime of the variant members of union class objects operated by memcpy

Open
#5,213 18 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TeX
Stars
221
Forks
813
Avg merge
16h 4m
Merged PRs (30d)
36

Description

Consider this example

union U{
   int i;
   char c;
};
U u1 = {.i = 1};  // #1
U u2 = {.c = 0};  // #2
std::memcpy(&u2, &u1, sizeof(U));  // #3

At #1, the variant member U::i of the object u1 is active, while at #2, the variant member U::c of the object u2 is active. Since [cstring.syn] p3 says

The functions memcpy and memmove are signal-safe. Both functions implicitly create objects ([intro.object]) in the destination region of storage immediately prior to copying the sequence of characters to the destination.

Thus, before the copying starts, what can be sure is that an object of type U is implicitly created in the specified storage. In addition, the lifetime of either U::i or U::c can start due to the "implicitly create objects" but not both. Which is regulated by [class.union.general] p2

At most one of the non-static data members of an object of union type can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.

Since, immediately prior to copying, we cannot determine which variant member has begun its lifetime in the newly created union object that occupies the storage of u2. Also, after the copying, we also cannot determine which one is active. Is it U::i because the corresponding variant is active in the source? Or, Is it U::c since it's the one selected by the "implicitly creating objects" operation.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the issue's union example and read the cited [cstring.syn], [intro.object], and [class.union.general] paragraphs. Determine how the active variant member's lifetime should be interpreted before and after memcpy, and clarify the standard wording so the resulting state is unambiguous.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.