How to store a C++ variable in a register

后端 未结 8 2071
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 23:26

I would like some clarification regarding a point about the storage of register variables: Is there a way to ensure that if we have declared a register variable in our code,

相关标签:
8条回答
  • 2020-12-15 23:52

    You can't. It is only a hint to the compiler that suggests that the variable is heavily used. Here's the C99 wording:

    A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

    And here's the C++11 wording:

    A register specifier is a hint to the implementation that the variable so declared will be heavily used. [ Note: The hint can be ignored and in most implementations it will be ignored if the address of the variable is taken. This use is deprecated (see D.2). —end note ]

    In fact, the register storage class specifier is deprecated in C++11 (Annex D.2):

    The use of the register keyword as a storage-class-specifier (7.1.1) is deprecated.

    Note that you cannot take the address of a register variable in C because registers do not have an address. This restriction is removed in C++ and taking the address is pretty much guaranteed to ensure the variable won't end up in a register.

    Many modern compilers simply ignore the register keyword in C++ (unless it is used in an invalid way, of course). They are simply much better at optimizing than they were when the register keyword was useful. I'd expect compilers for niche target platforms to treat it more seriously.

    0 讨论(0)
  • 2020-12-15 23:52

    The "register" keyword is a remnant of the time when compilers had to fit on machines with 2MB of RAM (shared between 18 terminals with a user logged in on each). Or PC/Home computers with 128-256KB of RAM. At that point, the compiler couldn't really run through a large function to figure out which register to use for which variable, to use the registers most effectively. So if the programmer gave a "hint" with register, the compiler would put that in a register (if possible).

    Modern compilers don't fit several times in 2MB of RAM, but they are much more clever at assigning variables to registers. In the example given, I find it very unlikley that the compiler wouldn't put it in a register. Obviously, registers are limited in number, and given a sufficiently complex piece of code, some variables will not fit in registers. But for such a simple example, a modern compiler will make i a register, and it will probably not touch memory until somewhere inside ostream& ostream::operator<<(ostream& os, int x).

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