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?

+2


source to share


4 answers


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.



+3


source


Placing specific variables or a group of variables in a memory segment is not a standard compiler function.



But some compiler supports special methods for this. Especially in embedded systems. For example, in Keil, I think you are on a statement to place a specific variable.

0


source


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.

0


source


0


source







All Articles