ddennis
ddennis

Reputation: 11

Initializing a static const array in c++

Let's say I have a class A which contains a static const int array like the following.

class A {
    static const int _array[];
    static int fn( int n );
}

Function fn includes very heavy calculation. And now I want to initialize my static const array using the function fn.

I did that in the following way:

//.cpp file
int A::fn (int n){
    ....
    return ....
}
const A::_array[] = {
    fn(0);
    fn(1);
    fn(2);
    ...
    fn(9);
}

My question is that whether the array initialization is in compile time? And how many times does the fn run if I use _array[i] in my other class methods? only 10 times in its initialization or it depends on how many times I use the _array?

EDIT: it was c++03 and is there any more efficient way to do this?

Upvotes: 0

Views: 1063

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

The array is initialized at run-time. But it will be initialized before the control will be passed to main. it could be initialized at compile time if it and the function would be defined as constexpr But such functions can not have very heavy calculations.

The function will be called as many times as there are its calls in the initialization list.

Also the correct definition of the array is

const int A::_array[] = {

Upvotes: 1

Related Questions