Question

I have written two short tests and compiled both with "g++ -S" (gcc version 4.7 on Arch Linux):

test1.cpp

inline int func(int a, int b) {
    return a+b;
}

int main() {
    int c = func(5,5);
    return 0;
}

test2.cpp

inline int func(const int& a, const int& b) {
    return a+b;
}

int main() {
    int c = func(5,5);
    return 0;
}

diff test1.s test2.s

1,5c1,5
<   .file   "test1.cpp"
<   .section    .text._Z4funcii,"axG",@progbits,_Z4funcii,comdat
<   .weak   _Z4funcii
<   .type   _Z4funcii, @function
< _Z4funcii:
---
>   .file   "test2.cpp"
>   .section    .text._Z4funcRKiS0_,"axG",@progbits,_Z4funcRKiS0_,comdat
>   .weak   _Z4funcRKiS0_
>   .type   _Z4funcRKiS0_, @function
> _Z4funcRKiS0_:
12a13,14
>   movl    8(%ebp), %eax
>   movl    (%eax), %edx
14c16
<   movl    8(%ebp), %edx
---
>   movl    (%eax), %eax
22c24
<   .size   _Z4funcii, .-_Z4funcii
---
>   .size   _Z4funcRKiS0_, .-_Z4funcRKiS0_
36,38c38,44
<   movl    $5, 4(%esp)
<   movl    $5, (%esp)
<   call    _Z4funcii
---
>   movl    $5, 20(%esp)
>   movl    $5, 24(%esp)
>   leal    20(%esp), %eax
>   movl    %eax, 4(%esp)
>   leal    24(%esp), %eax
>   movl    %eax, (%esp)
>   call    _Z4funcRKiS0_

However, I don't really know how to interpret the results. All I see is that test2 apparently generates longer code, but I can't really tell what the differences are.

A follow-up question: Does it matter with member functions?

Was it helpful?

Solution

const correctness is for humans, not for code generation

it makes it easier for humans to understand code, by introducing constraints on what can change

so, yes it matters for short functions also, since they can be called from code that is not as short and easy to comprehend in full at a glance

that said, your example functions do not illustrate const correctness

so, while this answers the literal question, probably you have misunderstood what const correctness is about, and meant to ask some other question, which i will refrain from guessing at

OTHER TIPS

Those functions aren't equivalent, one takes argument by value and the other by reference. Note that if you drop the references & then you are left with exactly the same functions, except that one enforces that you don't change the value of the copied arguments while the other doesn't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top