Checking if a variable is initialized

Viewed 146947

Seems like this would be a duplicate, but maybe it is just so obvious it hasn't been asked...

Is this the proper way of checking if a variable (not pointer) is initialized in a C++ class?

class MyClass
{
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        // define mDecimal.
    }
}
12 Answers

If you donot like boost and c++17, the google c++ lib Abseil is another method to realize that. absl::optional is just like std::optional.

#include <absl/types/optional.h>
class MyClass
{
    void SomeMethod();

    absl::optional<char> mCharacter;
    absl::optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if (mCharacter)
    {
        // do something with mCharacter.
    }

    if (!mDecimal)
    {
        // define mDecimal.
    }
}

You could reference the variable in an assertion and then build with -fsanitize=address:

void foo (int32_t& i) {
    // Assertion will trigger address sanitizer if not initialized:
    assert(static_cast<int64_t>(i) != INT64_MAX);
}

This will cause the program to reliably crash with a stack trace (as opposed to undefined behavior).

Related