views:

123

answers:

4

In C++, is it possible to force the compiler to arrange a series of global or static objects in a sequential memory position? 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 occupy a continuous chunk of memory, or is the compiler free to place them anywhere in the address space?

+3  A: 

The compiler can do as it pleases when it comes to placing static objects in memory; if you want better control over how your globals are placed, you should consider writing a struct that encompasses all of them. That will guarantee that your objects will all be packed in a sequential and predictable order.

Adam Maras
Just a follow-up: if all of the global objects you're concerned with are of the same type, you can just use an array to store all of them. That will also ensure contiguous storage.
Adam Maras
A: 

Placing specific variables or group of variables into a memory segment is not a standard feature of the compiler.

But some compiler supports special methods to do this. Especially in embedded systems. For example in Keil, I guess you at at operator to place a particular variable.

Alphaneo
A: 

The way to force objects to be in a contiguous piece of memory is to put them into an array.

If you use the built-in array type, the only way they can be initialized is their default constructors (although you can change their values later):

MyClass my_globals[3];

If you use 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 global variables are usually frowned upon. And rightly so.

sbi
Global variables can be changed into static class members, which at least wraps a class name around them.
Loadmaster
And what does that gain you?
sbi
A: 

Yes, some compilers now contain optimizations that will automatically do something like this for you:

e.g.

Automatic pool allocation: improving performance by controlling data structure layout in the heap

Restructuring field layouts for embedded memory systems

MPADS: memory-pooling-assisted data splitting

scurial