This question was asked today (Prefetching double class member requires casting to char*?), and the accepted solution was to prefetch the return value of a member function, that returned the member variable by reference.
However, it made me curious - if the member is less than a cache-line offset from the start of the object, doesn't the act of calling the member function of the object implicitly load the object into the cache, thus obviating the need for precaching the member? Would it not be more effective to prefetch the object without calling the member function (as suggested in my answer)?
Not quite. For example, look at this code.
It appears that there should be a null pointer error on the line
double* dp = dc->getDoubleAddr();
, given thatdc
isNULL
. But if you compile and run this, there is usually no exception.In the assembly code that is built from this, all the object methods, like
dc->getDoubleAddr()
, are transformed into standard functions with the first parameter being the address of the calling object (in this case,dc
). So calling the function does not cause a null pointer exception; the argument is merely 0x0.Then, in the code, getDoubleAddr returns the address of the double inside the object, given the object's address. There is no need to access memory here - the program already knows the object type and therefore the location of
double_
. It merely returns the address of the object, plus its eight-byte offset fromchar space[8]
, and the program prints out 0x8.