Your statement that static
will:
Allocate memory at compile time
This indicates a misconception. Static Storage Durration is defined:
The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static
or extern
.
Understanding Static Storage Duration is essential to combating the "static initialization fiasco".
With that understanding we can see that there is no performance benefit to constructing a static
pointer to a variable, such as static unique_ptr<const int> x(new int(13));
Instead just using the address of value_behind_x
as necessary is preferable.
The same thing applies to allocating an array with Static Storage Duration. You could use a container such as array
if you need container encapsulation of your array: static array<int, 10> x_array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
But generally speaking with the improvements to range access and container access provided by c++11, c++14, and c++17 in the iterator library I'd just suggest that you stick with:
static const x_array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
EDIT:
Just so you are aware, string literals also have Static Storage Duration, meaning that thy are not "allocated at compile time." In fact There are only 3 storage durations other than Static Storage Duration used by C++:
- Automatic Storage Duration. The object is allocated at the beginning of the enclosing code block and deallocated at the end. All local objects have this storage duration, except those declared
static
, extern
or thread_local.
- Thread Storage Duration. The object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. thread_local can appear together with
static
or extern
to adjust linkage.
- Dynamic Storage Duration. The object is allocated and deallocated per request by using dynamic memory allocation functions.
So no, there is no allocation or initialization before runtime. Nor do I expect there to ever be, as that would require a fundamental C++ ideology change and a computer architectural change at some level.