Organizing global / static objects sequentially in memory
In C ++, can the compiler be forced to organize a series of global or static objects in a sequential memory location? Or is this the default behavior? For example, if I write ...
MyClass g_first ("first");
MyClass g_second ("second");
MyClass g_third ("third");
... will these objects take up a contiguous chunk of memory, or can the compiler place them anywhere in the address space?
source to share
The compiler can do what it likes when it comes to allocating static objects in memory; if you want better control over how your global blocks are laid out, you should consider creating one struct
that covers all of them. This will ensure that your objects are packed in a consistent and predictable order.
source to share
The way to get objects to be in a contiguous chunk of memory is to put them in an array.
If you are using the built-in array type, the only way they can be initialized is through their default constructors (although you can change their values ββlater):
MyClass my_globals[3];
If you are using a dynamic array (called std::vector
in C ++), you are more flexible:
namespace {
typedef std::vector<MyClass> my_globals_type;
my_globals_type init_my_globals()
{
my_globals_type globals;
globals.push_back(MyClass("first"));
globals.push_back(MyClass("second"));
globals.push_back(MyClass("third"));
return globals;
}
my_globals_type my_globals = init_my_globals();
}
Note that globals are generally frowned upon. And it is right.
source to share
Yes, some compilers now contain optimizations that will automatically do something like this for you:
eg.
Automatic pool allocation: improve performance by managing the data structure on the heap
source to share