Skip to content

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

Open
@xmh0511

Description

@xmh0511

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions