简体   繁体   中英

Member access through pointer to object

On the stack the compiler is free to do a lot of optimizations, because the context is static and known at compile time, but when dealing with access to dynamically allocated objects and generally accessing "by reference" the context is not known, so logically in such cases, member access boils down to dereferencing a memory address derived by adding the object base address and the offset for that member. Or does it? I am pretty new to this, so at this point I am only guessing and probably missing a lot of details.

For example I noticed that if I implement the + operator as void add(int * a, int * b, int * r); when working with stack members (and using the & operator) the assembly code is identical to that the regular + operator creates, so it does seem that pointers which are known to point to compile time known values are are being optimized to exclude extra dereferencing (and copying) and the indirections inside the add() function are inlined as direct access to stack objects. Does this mean the compiler is "good enough" to be able to optimize say accessors implemented with indirection from constant value offsets from the object base address on the stack as if using struct member access to get that value?

I don't know how you implemented the body of the function so this answer might be completely off :).

If you are adding inside your function r = a + b , the code will look the same but won't be the same.

for the prototype (int *, int * , int *) you will add pointers which is wrong. To get the integer value inside your function, the body should be :

*r = *a + *b ; 

OR

r[0] = a[0] + b[0];

in order to get the value which you desire. This body shouldn't have the same assembly code as the + operator since the values pointed aren't the known at compile time.

for the prototype (int &, int & , int &) and the body

r = a + b;

the compiler will inline this function, so yes, the assembly should be indentical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM