Tyler
Tyler

Reputation: 322

Static memory allocation for array of objects in c++

Note: C++98 is the only standard available

I'm trying to create an large array to use as a lookup table during runtime, but I know all the table information at compile time. Conceptually I know I can get a lot of run time savings with static allocation but I'm having some trouble with the C++ syntax for this.

Or, simply put, I'm looking the correct way to do a the class version of

const int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

To get as much savings as I can from knowing everything I want to store in the array of objects at compile time.

Here's an example of my class for entries

class foo{
  private:
    const int a;
    const char * b;
  public:
    foo(const int a, const char * b);
    int get_a(void) const{
      return this->a;
    }
    const char * get_b(void) const{
      return this->b;
    }
};

foo::foo(
         const int a,
         const char * b
       ) :
          a(a),
          b(b){
}

Can run with this main

//Is this array statically allocated at compile time or dynamically allocated at run time with the constructors of foo?
foo arr[2]={
  foo(0,"b0"),
  foo(1,"b1")
};

int main(void){
  for(int i=0;i<2;i++){
    std::cout<<arr[i].get_a()<<std::endl;
    std::cout<<arr[i].get_b()<<std::endl;
  }
  return 0;
}

Upvotes: 1

Views: 2298

Answers (2)

Yola
Yola

Reputation: 19043

There is no way to tell for sure at which time initialization happens. To check it with your compiler you can set a breakpoint in the constructor and run it in release mode.

Upvotes: 0

Johan
Johan

Reputation: 3881

The array arr is allocated statically at compile-time but whether it is initialized at compile-time or run-time can differ between compilers. The safe bet is that your compiler initializes the array at run-time but there are compilers that can use compile-time initialization instead of run-time initialization if the constructors are simple enough.

In C++11 and later you can declare the constructor of foo as constexpr to make the compiler initialize arr at compile time.

Upvotes: 2

Related Questions