Structure not in memory

前端 未结 1 447
失恋的感觉
失恋的感觉 2021-01-23 02:00

I created a structure like that:

struct Options {
    double bindableKeys = 567;
    double graphicLocation = 150;
    double textures = 300;
};
Options options;         


        
相关标签:
1条回答
  • 2021-01-23 02:42

    Contrary to popular belief, C++ source code is not a sequence of instructions provided to the executing computer. It is not a list of things that the executable will contain.

    It is merely a description of a program.

    Your compiler is responsible for creating an executable program, that follows the same semantics and logical narrative as you've described in your source code.

    Creating an Options instance is all well and good, but if creating it does not do anything (has no side effects) and you never use any of its data, then it may as well not exist, and therefore is not a part of the logical narrative of your program.

    Consequently, there is no reason for the compiler to put it into the executable program. So, it doesn't.

    Some people call this "optimisation". That the instance is "optimised away". I prefer to call it common sense: the instance was never truly a part of your program.

    And even if you do use the data in the instance, it may be possible for an executable program to be created that more directly uses that data. In your case, nothing changes the default values of Option's members, so there is no reason to include them into the program: the if statement can just have 567 baked into it. Then, since it's baked in, the whole condition becomes the constant expression 567 > 10 which must always be true; you'll likely find that the resulting executable program consequently contains no branching logic at all. It just starts up, then outputs "test" over and over again until you force-terminate it.

    That all being said, because we live in a world governed by physical laws, and because compilers are imperfect, there is always going to be some slight leakage of this abstraction. For this reason, you can trick the compiler into thinking that the instance is "used" in a way that requires its presence to be represented more formally in the executable, even if this isn't necessary to implement the described program. This is common in benchmarking code.

    0 讨论(0)
提交回复
热议问题