Checking if a variable is initialized

前端 未结 13 1451
后悔当初
后悔当初 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:13

    Depending on your applications (and especially if you're already using boost), you might want to look into boost::optional.

    (UPDATE: As of C++17, optional is now part of the standard library, as std::optional)

    It has the property you are looking for, tracking whether the slot actually holds a value or not. By default it is constructed to not hold a value and evaluate to false, but if it evaluates to true you are allowed to dereference it and get the wrapped value.

    class MyClass
    {
        void SomeMethod();
    
        optional mCharacter;
        optional mDecimal;
    };
    
    void MyClass::SomeMethod()
    {
        if ( mCharacter )
        {
            // do something with *mCharacter.
            // (note you must use the dereference operator)
        }
    
        if ( ! mDecimal )
        {
            // call mDecimal.reset(expression)
            // (this is how you assign an optional)
        }
    }
    

    More examples are in the Boost documentation.

提交回复
热议问题