What are the dangers of uninitialised variables?

前端 未结 4 1522
-上瘾入骨i
-上瘾入骨i 2021-01-18 20:38

In a program I am writing I currently have several uninitialised variables in my .h files, all of which are initialised at run-time. However, in Visual Studio it warns me ev

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 21:13

    You have not included the source so we have to guess about why it happens, and I can see possible reasons with different solutions (except just zero-initializing everything):

    1. You don't initialize at the start of the constructor, but you combine member initialization with some other code that calls some functions for the not fully initialized object. That's a mess - and you never know when some functions will call another function using some non-initialized member. If you really need this, don't send in the entire object - but only the parts you need (might need more refactoring).
    2. You have the initialization in an Init-function. Just use the recent C++-feature of having one constructor call another instead.
    3. You don't initialize some members in the constructor, but even later. If you really don't want to initialize it having a pointer (or std::unique_ptr) containing that data, and create it when needed; or don't have it in the object.

提交回复
热议问题