I’ve been trying to implement my own version of std::inplace_vector
in C++26; that is, a dynamically-resizable array with compile-time fixed capacity, that also allows non-default-constructible elements to be stored.
At the outset, the only way I could think of having non-default-constructible elements to be stored was to keep a union
of a T array[N];
as a field. This is because I previously read that a single-element union can be used to prevent the immediate initialization of that element (source), which is needed here to prevent the automatic default construction of the T
values. Then, I would use placement-new
/delete
(or, well, actually std::allocator_traits<Allocator>
) to directly initialize and destruct elements when needed.
However, I just thought of a possible issue. I think I remember hearing that in C++, one is not allowed to assign an object with size N
bytes to any uninitialized sequence of N
raw bytes, because the object’s “lifetime” has to have begun. In that case, if I were to default-construct a my_inplace_vector
, wouldn’t I be disallowed from actually assigning directly to any of the elements (i.e. my_inplace_vector[1] = some initializer
), because wrapping the field array
in an union
prevents the lifetime of its elements from starting?
I’ve read the cppreference page on lifetimes, but I cannot find where the relevant section is for objects contained within an array contained within an union, so I am unsure of if the lifetimes work out in this case. Can someone explain the rules to me?
9