Checking if a variable is initialized

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

    If you mean how to check whether member variables have been initialized, you can do this by assigning them sentinel values in the constructor. Choose sentinel values as values that will never occur in normal usage of that variable. If a variables entire range is considered valid, you can create a boolean to indicate whether it has been initialized.

    #include 
    
    class MyClass
    {
        void SomeMethod();
    
        char mCharacter;
        bool isCharacterInitialized;
        double mDecimal;
    
        MyClass()
        : isCharacterInitialized(false)
        , mDecimal( std::numeric_limits::quiet_NaN() )
        {}
    
    
    };
    
    
    void MyClass::SomeMethod()
    {
        if ( isCharacterInitialized == false )
        {
            // do something with mCharacter.
        }
    
        if ( mDecimal != mDecimal ) // if true, mDecimal == NaN
        {
            // define mDecimal.
        }
    }
    

提交回复
热议问题