How are local and global variables initialized by default?

后端 未结 10 1676
粉色の甜心
粉色の甜心 2020-11-30 10:39

Based on below, am i right?

  • global_A reference is initialized to null.
  • global_int is 0
  • local_A reference is null
  • local_int is uninit
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 10:58

    Basically, whenever you declare a variable, the compiler will call its default constructor unless you specify otherwise.

    The language level types (e.g. pointers, 'int', 'float', 'bool', etc) "default constructor" does absolutely nothing, it just leaves the memory as it is when it is declared (global/static variables are special cases, refer to chubsdad's answer for more on the specifics). This means that they can be pretty much anything because you usually can't be sure what was in that memory previously or even where the memory came from (except in the case of the 'placement new' operator).

    The class you created has no constructors so the compiler will generate a default constructor for you which simply calls the constructor of each of its members/variables. If you incorporate the information provided in the previous paragraph, you can see that the variable 'x' will have its default constructor called, which does nothing, and thus is isn't initialized to any value.

    As others have said, there are no references in your code or pointers, so the term 'NULL' is invalid in all cases here. NULL usually refers to a pointer which, like other language level types, doesn't get set to anything until you assign it a value (unless of course its a global/static variable).

提交回复
热议问题