I just had a discussion about the fact that references in C++ are useless since everything can be done with pointers and references only cause confusion when used in conjunction with pointers. There was some disbelief that references are, underneath, implemented identically to pointers and only vary syntactially. I would avoid using the phrase synatic sugar
since they aren't really...uhhh...sweet.
To settle the argument, I compiled the following two code snippits:
void swapByPtr (int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
void swapByRef (int& a, int& b){
int t = a;
a = b;
b = t;
}
Under GCC for Intel, they both produced the following code, less labels and a few directives:
pushl %ebp movl %esp, %ebp subl $4, %esp movl 8(%ebp), %eax movl (%eax), %eax movl %eax, -4(%ebp) movl 8(%ebp), %edx movl 12(%ebp), %eax movl (%eax), %eax movl %eax, (%edx) movl 12(%ebp), %edx movl -4(%ebp), %eax movl %eax, (%edx) leave ret
However, they produce the following directives:
.globl _Z9swapByPtrPiS_ .type _Z9swapByPtrPiS_, @function _Z9swapByPtrPiS_: code here .size _Z9swapByPtrPiS_, .-_Z9swapByPtrPiS_
.globl _Z9swapByRefRiS_ .type _Z9swapByRefRiS_, @function _Z9swapByRefRiS_: code here .size _Z9swapByRefRiS_, .-_Z9swapByRefRiS_
The strange labels are created to handle function overloading. They do show differences between int* and int&. So, although the code is identical, C++ synatically differentiates them.
| Mon, 8 Dec 2008 22:26:15 -0500 |
|