Where are variables in C++ stored?

2020-02-04 11:47发布

Where are variables in C++ stored?

Inside the RAM or the processor's cache?

9条回答
Emotional °昔
2楼-- · 2020-02-04 12:43

depending on how they are declared, they will either be stored in the "heap" or the "stack"

The heap is a dynamic data structure that the application can use.

When the application uses data it has to be moved to the CPU's registers right before they are consumed, however this is very volatile and temporary storage.

查看更多
Animai°情兽
3楼-- · 2020-02-04 12:46

For C++ in general, the proper answer is "wherever your compiler decides to put them". You should not make assumptions otherwise, unless you somehow direct your compiler otherwise. Some variables can be stored entirely in registers, and some might be totally optimized away and replaced by a literal somewhere. With some compilers on some platforms, constants might actually end up in ROM.

The part of your question about "the processor's cache" is a bit confused. There are some tools for directing how the processor handles its cache, but in general that is the processor's business and should be invisible to you. You can think of the cache as your CPU's window into RAM. Pretty much any memory access goes through the cache.

On the other end of the equation, unused RAM sometimes will get swapped out to disk on most OSes. So its possible (but unlikely) that at some moments your variables are actually being stored on disk. :-)

查看更多
干净又极端
4楼-- · 2020-02-04 12:48

C++ is not aware of your processor's cache.

When you are running a program, written in C++ or any other language, your CPU will keep a copy of "popular" chunks of RAM in a cache. That's done at the hardware level.

Don't think of CPU cache as "other" or "more" memory...it's just a mechanism to keep some chunks of RAM close by.

查看更多
登录 后发表回答