Data member, assigned once at runtime, const thereafter.

Hi,

I have an int data member in a class that is assigned a value at instantiation and thereafter remains constant until destruction.

This data member, n, is the limit for a large number of loops, and the loop code generated is expensive because I can't mark it const:

; 150 : // invert Lower Triangle;
; 151 : for( int i=0; i < n; i++ ){

inc r9d
add rbx, 8
add r8, 8
cmp r9d, DWORD PTR [r11+56] <<< compare i < n
jl SHORT $LL13@MultPC
mov rbx, QWORD PTR [rsp+16]

Is there a way to mark n as const after it is assigned once?

(Note: this is of necessity MSVC9; thus circa C99)

Cheers.
Last edited on
If it is only given a value at the instantiation of the class, can't you mark it as const and initialise it in the initialiser list of the constructor?
Unfortunately not.

The object is populated with data from a file; n varies with the size of the file; but once loaded doesn't change.

n is then used as the bound in literally dozens of loops; and the code is indirecting for every iteration of every loop, rather than just loading the value into a register and comparing.

I can work around it by having

1
2
3
4
5
6
7
8
9
10
class::method ( ... ) {
    const int nn = n;

...

    for( int i=0; i < nn; ++ i ) {
        ...
    }
...
}


But as there are actually half a dozen of these limits for various loops I end up with something like this at the top of many methods:

const int NNumBlockLabels = NumBlockLabels, NNumNodes = NumNodes, NNumLineProps = NumLineProps, NNumEls = NumEls, NNumPBCs = NumPBCs;

which is less than nice :)

Cheers, Buk.
Last edited on
Topic archived. No new replies allowed.