问题
I am writing a simple VM and I have a question on implementing object and structure member access.
Since the begin address of a program is arbitrary on each run, and subsequently the address of each and every of its objects is arbitrary too.
Thus the only way I can think of to access an object or its member object is by accessing an offset from the "base" pointer, which means there is an arithmetic operation needed to access anything in a program structure.
My question is whether this is the way it is done in professional compilers, because obviously this approach adds some overhead to the runtime, and I myself can't think of any way to offload this process from the runtime because of the lack of guarantees for consistency of memory allocation and its address?
回答1:
Most computers for many decades provide addressing modes that let you specify the address as a combination of a base and an offset, and the actual calculation is carried out in the hardware for no additional cost in CPU clock cycles.
More recent (past few decades) computers offer hardware for virtualizing memory layout, meaning that even through the physical address of an item is different on every run, its address in the virtual address space remains the same. Again, there is no additional cost for using the base address, because the calculations are performed implicitly and invisibly to the executing binary code of a program.
来源:https://stackoverflow.com/questions/11490085/object-and-struct-member-access-and-address-offset-calculation