Does an unused member variable take up memory?

前端 未结 6 1932
一生所求
一生所求 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:54

    It's dependent on your compiler and its optimization level.

    In gcc, if you specify -O, it will turn on the following optimization flags:

    -fauto-inc-dec 
    -fbranch-count-reg 
    -fcombine-stack-adjustments 
    -fcompare-elim 
    -fcprop-registers 
    -fdce
    -fdefer-pop
    ...
    

    -fdce stands for Dead Code Elimination.

    You can use __attribute__((used)) to prevent gcc eliminating an unused variable with static storage:

    This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced.

    When applied to a static data member of a C++ class template, the attribute also means that the member is instantiated if the class itself is instantiated.

提交回复
热议问题