Do static members of a class occupy memory if no object of that class is created?

前端 未结 3 553
旧时难觅i
旧时难觅i 2020-12-01 06:54

Say I have a class and I have a static member in it, but I don\'t create any objects of that type. Will the memory be occupied for the static variable? If it would be occupi

3条回答
  •  遥遥无期
    2020-12-01 07:28

    The C++ standard doesn't explicitly state when static memory is allocated, as long as it is available on first use. That said, it is most likely allocated during program initialization, thus guaranteeing its presence as soon as it is required, without needing special-case code to detect and perform allocation on access.

    The purpose of putting static data into a class is the same as putting any other data into classes. By putting the data into a class structure, you are defining an encapsulating namespace, as well as being able to control access using accessor and mutator methods; this, in turn, will allow you to validate data going into the static memory store, and to ensure consistency throughout the use of this data.

提交回复
热议问题