Understanding C++ operator overloading -


i reading source of hashing competition today, , came across this:

#define bytes_in_block 1024  struct block{     uint8_t v[bytes_in_block];      block(){ memset(v, 0, bytes_in_block); }     uint64_t& operator[](uint8_t i){ return *(uint64_t*)(v + 8 * i); } }; 

then, little later in code, there's this:

state = new block[cost]; // cost uint32_t (like 1024) // 50 lines of code. block prev_block;  prev_block = state[foo]; // foo uint32_t 

what can't figure out doing. now, understand c, c++ not much. bear me here second.

this part: return *(uint64_t*)(v+8*i) should return uint64_t, , when tested it:

state->v[8*10] = 12; uint64_t bar = *(uint64_t*)(v+8*10); printf("%" priu64 "\n", bar); 

so makes sense.

but this:

prev_block = state[foo];

makes no sense. since state block*, prev_block should "be" state, correct? doesn't, because arrays different.

state->v[8*12] = 12; printf("%" priu64 "\n", (*state)[12]); prev_block = state[12]; printf("%" priu64 "\n", (*(&prev_block))[12]); 

so, going on here?

you mixing 2 operator[]s involved here. in last example, set state[0][12] = 12, , you're comparing state[12][12]. since state block*, state[n] normal array access; doesn't invoke operator[] defined in block.


Comments