Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the C++ standard guarantee regarding the storage, allocation of local variables?

Let's consider this simple C++ code:

struct vector3d { double x, y, z; };

void foo()
{
    vector3d v;
    ...
}

What does C++ say about the location of v? My guess would be: nothing, and that would make sense as C++ should not bother with such underlying memory concepts.

But if the C++ standard does not talk about the specific concepts of stack, heap and thus dynamic memory allocation, how does it guarantee in such case that the compiler would not choose to translate this line with an underlying call to malloc instead of a classic sub rsp, X?

In the case it does not guarantee anything, does C guarantee something (out of curiosity)? Is it just widely assumed by all C++ developers that this will be on the stack?

Thanks!

like image 569
AntiClimacus Avatar asked Dec 11 '22 06:12

AntiClimacus


1 Answers

You're correct that the C++ standard does not directly say anything about this. Indeed, concepts such as "stack" or "heap" do not make sense from the standard's POV.

This is effectively a Quality Of Implementation issue, and other than the hypothetical Hell++ (whose motto would be to "stick to RAW and violate RAI as much as possible"), no compiler has a reason to store automatic-duration local variables on the heap.

like image 138
Angew is no longer proud of SO Avatar answered May 23 '23 06:05

Angew is no longer proud of SO