How are rvalues in c++ stored in memory?

后端 未结 2 1086
感动是毒
感动是毒 2021-02-08 15:05

Trying to learn lvalues, rvalues and memory allocation for them. So with a lot of learning materials there is a bit of chaos.

An rvalue

相关标签:
2条回答
  • 2021-02-08 15:11

    Short answer: it's implementation dependent.

    The main reasoning behind this is as always freedom for the compiler to improve performances of your code. A more concrete way to understand this is to remember that a value can be stored in a register of your CPU and never actually be in your memory which more or less means that the value has no address. I won't bet everything i have on it but this is probably one of the main reasons why "we cannot get an address of an rvalue".

    In a more general way since an rvalue is semantically temporary it is more likely to be put in temporary places or optimised in a way where it cannot easily be mapped to an address and even if it can that would be counter productive in terms of performance.

    0 讨论(0)
  • 2021-02-08 15:27

    Conceptually, rvalues live on the "stack". If you get to their address, it is conceptually an address somewhere on the stack. If the address isn't taken at all, the entity may never really come into existence as long as the compiler sets up the correct instructions to have it appear as if it were created.

    Even if the entity is really created where exactly it resides depends on various things and it may even end up not being on the stack at all: it may be in the current stack frame but it may also be an other stack frame or in some destintation if the rvalue ends up being copied/moved there and the compiler does copy-elision. If the rvalue ends up being bound to a const& it may also reside somewhere else than it would if it didn't.

    The life-time of the rvalue is bound by the language rules. How that is actually implemented is pretty much up to the compiler and/or the ABI it adheres to.

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