Checking if a variable is initialized

前端 未结 13 1442
后悔当初
后悔当初 2020-12-28 11:59

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 init

13条回答
  •  攒了一身酷
    2020-12-28 12:30

    With C++17 you can use std::optional to check if a variable is initialized:

    #include 
    #include   // needed only for std::cout
    
    int main() {
        std::optional variable;
    
        if (!variable) {
            std::cout << "variable is NOT initialized\n";
        }
    
        variable = 3;
    
        if (variable) {
            std::cout << "variable IS initialized and is set to " << *variable << '\n';
        }
    
        return 0;
    }
    

    This will produce the output:

    variable is NOT initialized
    variable IS initialized and is set to 3
    

    To use std::optional in the code snipped you provided, you'll have to include the standard library header and add std::optional<...> to the respective variable declarations:

    #include 
    
    class MyClass
    {
        void SomeMethod();
    
        std::optional mCharacter;
        std::optional mDecimal;
    };
    
    void MyClass::SomeMethod()
    {
        if ( mCharacter )
        {
            std::cout << *mCharacter;  // do something with mCharacter.
        }
    
        if ( ! mDecimal )
        {
            mDecimal = 3.14159;  // define mDecimal.
        }
    }
    

提交回复
热议问题