Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

union — shared storage for alternative members

The union keyword defines a class type whose non-static data members share storage. At most one member can be active at a time; correct use requires tracking member lifetimes.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

union Name { Type1 member1; Type2 member2; };

union defines a class type that stores alternative values in shared storage. Its size is sufficient for its largest non-static data member, but need not equal that member's size exactly. A union does not automatically record which member is active.

A member is active when its lifetime has begun and has not ended. In the example, Value value{42} activates count. Assigning value.ratio = 0.5 starts the lifetime of ratio and ends the lifetime of count. This simple switch works for the scalar types shown; do not generalize it to arbitrary class types.

Reading an inactive member generally causes undefined behavior—it is not a portable way to reinterpret bits. Narrow exceptions exist, such as inspecting the common initial sequence of standard-layout structs when the standard's conditions hold. After the switch in the example, do not read value.count.

Members with non-trivial constructors or destructors may require explicit destruction and construction through placement new. This entry targets C++23; the supplied source is an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

union Value {
    int count;
    double ratio;
};

int main() {
    Value value{42};
    std::cout << value.count << '\n';

    value.ratio = 0.5;
    std::cout << value.ratio << '\n';
}

Result

42
0.5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources