The standard says that reading from an uninitialized variable is undefined behavior. However, suppose I want to construct std::array of uninitialized values of user-defined type Z, which is in fact initialized by default. Can one achieve something like the following without causing UB?
struct Uninitialized{};
struct Z{
Z() : x_{} {}
Z(Uninitialized) {}
int x_;
};
std::array<Z, 2> A{Z{Uninitialized{}}, Z{Uninitialized{}};
The use case for this would be to identify uninitialized values using sanitizers when working with arrays(without sacrificing initialization of x_ in default constructor of Z).
auto uz = Z{Uninitialized{}};
std::array<Z, 5> A{uz, uz, uz, uz, uz};
// ... some tedious computations where A[4].x_ remains uninitialized
// due to incorrect implementation(maybe off-by-1).
// ... print A to file
I tried running the code above in a somewhat different setting and it worked as expected using Valgrind.
slobod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1