I've just begun learning C++ and I wanted to get my head around the different ways to create variables and what the different keywords mean. I couldn't find any description that really went through it, so I wrote this to try to understand what's going on. Have I missed anything? Am I wrong about anything?
Global Variables
Global variables are stored neither on the heap nor stack.
static
global variables are non-exported (standard global variables can be accessed with extern
, static
globals cannot)
Dynamic Variables
Any variable that is accessed with a pointer is stored on the heap.
Heap variables are allocated with the new
keyword, which returns a pointer to the memory address on the heap.
The pointer itself is a standard stack variable.
Variables inside {} that aren't created with new
Stored in the stack, which is limited in size so it should be used only for primitives and small data structures.
static
keyword means the variable is essentially global and stored in the same memory space as global variables, but scope is restricted to this function/class.
const
keyword means you can't change the variable.
thread_local
is like static
but each thread gets its own variable.
Register
A variable can be declared as register
to hint to the compiler that it should be stored in the register.
The compiler will probaby ignore this and apply it to whatever it thinks would be the best improvement.
Typical usage would be for an index or pointer being used as an interator in a loop.
Good practice
- Use
const
by default when applicable, its faster. - Be wary of
static
and globals in multithreaded applications, instead usethread_local
or mutex - Use
register
on iterators
Notes
Any variables created inside a function (non-global) that is not static
or thread_local
and is not created with new
, will be on the stack. Stack variables should not exceed more than a few KB in memory, otherwise use new
to put it on the heap.
The full available system memory can be used for variables with static
keyword, thread_local
keyword, created with new
, or global.
Variables created with new
need to be freed with delete
. All others are automatically freed when they're out of scope, except static
, thead_local
and globals which are freed when the program ends.
Despite all the parroting about how globals should not be used, don't be bullied: they are great for some use cases, and more efficient than variables allocated on the heap. Mutexes will be needed to avoid race conditions in multi-threaded applications.