Does a constant inside a object method live in the stack?

Viewed 43

Consider this method of the class CameraTab

void CameraTab::onFocusWheelTick(int delta)
{
    const int lut[] = {0,1,3,6,8,16,32,62,90,120,240,500,700,900,1000};
    const int lut_len = sizeof(lut)/sizeof(lut[0]);
    ...
}

Does all the instances of this class share the same lut[] array? Is it created and destroyed in the stack on every method call?

1 Answers

To frame the answer in pedantic C++ terms: each C++ compiler is free to make any optimization that has no observable difference. What your question is: would this optimization have no observable difference? It seems at first glance that constructing the array and the variable in static scope, just once, would have no observable difference. It can't be modified. It's always the same. So, why not?

But it does have an observable difference, potentially. It's the address of the array, or a pointer to an array. Pointers in C++ have certain semantical requirements, specifically with respect to their total order, as implemented by comparison function objects. With different execution threads, or even a single execution thread that invokes this function recursively, you will have different logical instances of these variables. Pointers to these objects would be all the same if they get constructed in static scope. This will violate their relative total order requirement.

That's an observable difference. So, unless the compiler can logically prove that no pointers to multiple instances of these objects will ever exist, the compiler has no choice but to construct them in automatic scope (on the stack).

And if your compiler can prove that there's no observable difference in your program: compilers are allowed, but not required, to make any such optimization, so whether your objects will get constructed in static scope or automatic scope will then be entirely at your compiler's discretion.

Related