Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

architecture - Where are variables in C++ stored?

Where are variables in C++ stored?

Inside the RAM or the processor's cache?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Named variables are stored:

  • On the stack, if they're function-local variables.
    C++ calls this "automatic storage"1 and doesn't require it to actually be the asm call stack, and in some rare implementations it isn't. But in mainstream implementations it is.
  • In a per-process data area if they are global or static.
    C++ calls this "static storage class"; it's implemented in asm by putting / reserving bytes in section .data, .bss, .rodata, or similar.

If the variable is a pointer initialized with int *p = new int[10]; or similar, the pointer variable p will go in automatic storage or static storage as above. The pointed-to object in memory is:

  • On the heap (what C++ calls dynamic storage), allocated with new or malloc, etc.
    In asm, this means calling an allocator function, which may ultimately get new memory from the OS via some kind of system call if its free-list is empty. "The heap" isn't a single contiguous region in modern OSes / C++ implementations.

C and C++ don't do automatic garbage collection, and named variables can't themselves be in dynamic storage ("the heap"). Objects in dynamic storage are anonymous, other than being pointed-to by other objects, some of which may be proper variables. (An object of struct or class type, as opposed to primitive types like int, can let you refer to named class members in this anonymous object. In a member function they even look identical.)

This is why you can't (safely/usefully) return a pointer or reference to a local variable.


This is all in RAM, of course. Caching is transparent to userspace processes, though it may visibly affect performance.

Compilers may optimize code to store variables in registers. This is highly compiler and code-dependent, but good compilers will do so aggressively.


Footnote 1: Fun fact: auto in C++03 and earlier, and still in C, meant automatic storage-class, but now (C++11) it infers types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...