How rvalues ​​in C ++ are stored in memory?

Trying to find out lvalues , rvalues and allocating memory for them. So with a lot of training materials there is a bit of chaos.

An rvalue is a value that should exist only within the expression in which it was created (before C ++ 11, at least). Thus, it has an address and a block of memory that it occupies. But by definition, we cannot get the rvalue address because it is a temporary object, unlike lvalue . But even before C ++ 11, we managed to get the rvalue address by returning it from the function and saving it to the link type const (well, I think, not the address, but the value).

So, more precisely, how does the rvalue distribution work? How long does a program or OS really remember that the memory location where the rvalue was created and marked as allocated, and another object cannot take its place?

As I see it, rvalues are now stored in the same way as lvalues , but we just have other rights to access them. And they have other types of exemption - for lvalues going out of scope, for rvalues you can optimize the existence within the expression or until there are no more references to it.

+5
source share
2 answers

Short answer: it is implementation dependent.

The main reason for this is, as always, the compiler’s freedom to improve the performance of your code. A more specific way to understand this is to remember that the value can be stored in the register of your CPU and never be in your memory, which more or less means that the value has no address. I will not bet on everything that I have, but this is probably one of the main reasons why "we can not get the rvalue address".

More generally, since rvalue is semantically temporary, it is most likely placed in temporary places or optimized in such a way that it cannot be easily matched with an address, and even if it can be counterproductive in terms of performance.

+5
source

Conceptually, rvalues ​​live on a stack. If you get to their address, this is conceptually an address somewhere on the stack. If the address is not accepted at all, the object can never exist until the compiler sets the correct instructions to make it look as if it were created.

Even if an object is actually created where it is located exactly, it depends on different things, and it may not even appear on the stack at all: it may be in the current frame of the stack, but it may also be a different frame of the stack or for some reason, if rvalue ends up copying / moving there, and the compiler does the copying. If the rvalue value is bound to const& , it could also be somewhere else than if it weren’t.

The rvalue lifetime is bound by language rules. How this is actually implemented depends heavily on the compiler and / or the ABI it adheres to.

+4
source

Source: https://habr.com/ru/post/1237919/


All Articles