Does an unused member variable take up memory?

前端 未结 6 1940
一生所求
一生所求 2020-12-13 03:00

Does initializing a member variable and not referencing/using it further take up RAM during runtime, or does the compiler simply ignore that variable?

struct         


        
6条回答
  •  心在旅途
    2020-12-13 03:59

    In general, you have to assume that you get what you have asked for, for example, the "unused" member variables are there.

    Since in your example both members are public, the compiler cannot know if some code (particularly from other translation units = other *.cpp files, which are compiled separately and then linked) would access the "unused" member.

    The answer of YSC gives a very simple example, where the class type is only used as a variable of automatic storage duration and where no pointer to that variable is taken. There, the compiler can inline all the code and can then eliminate all the dead code.

    If you have interfaces between functions defined in different translation units, typically the compiler does not know anything. The interfaces follow typically some predefined ABI (like that) such that different object files can be linked together without any problems. Typically ABIs do not make a difference if a member is used or not. So, in such cases, the second member has to be physically in the memory (unless eliminated out later by the linker).

    And as long as you are within the boundaries of the language, you cannot observe that any elimination happens. If you call sizeof(Foo), you will get 2*sizeof(int). If you create an array of Foos, the distance between the beginnings of two consecutive objects of Foo is always sizeof(Foo) bytes.

    Your type is a standard layout type, which means that you can also access on members based on compile-time computed offsets (cf. the offsetof macro). Moreover, you can inspect the byte-by-byte representation of the object by copying onto an array of char using std::memcpy. In all these cases, the second member can be observed to be there.

提交回复
热议问题