Skip to content

Instantly share code, notes, and snippets.

@chfast
Created January 16, 2018 13:26
Show Gist options
  • Save chfast/4ebd3bf1d6a1427e8ca222a40ea88470 to your computer and use it in GitHub Desktop.
Save chfast/4ebd3bf1d6a1427e8ca222a40ea88470 to your computer and use it in GitHub Desktop.
How to explicity uninitialize variables in C++

How to explicity uninitialize variables in C++

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;
}

@hedgehog1024
Copy link

Just for comparison:

struct Complex {
    re: f64,
    im: f64,
}

fn main() {
    let x: Complex = unsafe { std::mem::uninitialized() };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment