struct uninitialized_t
{
template<typename T>
operator T() const noexcept
{
char data alignas(T)[sizeof(T)];
return *reinterpret_cast<T*>(data);
}
};
static constexpr uninitialized_t uninitialized;
struct Complex
{
double re = 0.0 / 0.0;
double im = 0.0 / 0.0;
};
void read_complex(Complex* z) noexcept;
void read_number(int* x) noexcept;
int test_initialized_int()
{
int x = 0;
read_number(&x);
return x;
}
int test_uninitialized_int()
{
int x = uninitialized;
read_number(&x);
return x;
}
Complex test_initialized_complex()
{
Complex z;
read_complex(&z);
return z;
}
Complex test_uninitialized_complex()
{
Complex z = uninitialized;
read_complex(&z);
return z;
}
Created
January 16, 2018 13:26
-
-
Save chfast/4ebd3bf1d6a1427e8ca222a40ea88470 to your computer and use it in GitHub Desktop.
How to explicity uninitialize variables in C++
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just for comparison: