Checking if a variable is initialized

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

    There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically).

    Instead, what you need to do is provide constructor(s) that initialize your class to a valid state. Static code checkers (and possibly some compilers) can help you find missing variables in constructors. This way you don't have to worry about being in a bogus state and the if checks in your method can go away completely.

提交回复
热议问题