简体   繁体   English

const正确性与短内联函数有关系吗?

[英]Does const-correctness matter with short inline functions?

I have written two short tests and compiled both with "g++ -S" (gcc version 4.7 on Arch Linux): 我编写了两个简短的测试,并使用“ g ++ -S”(Arch Linux上的gcc版本4.7)进行了编译:

test1.cpp test1.cpp

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

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

test2.cpp 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 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. 我所看到的只是test2显然会生成更长的代码,但是我无法真正分辨出它们之间的区别。

A follow-up question: Does it matter with member functions? 后续问题:与成员函数有关系吗?

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. 请注意,如果删除引用&则剩下的功能完全相同,只是一个函数强制您不要更改复制参数的值,而另一个函数则不要更改。

const correctness is for humans, not for code generation const正确性是为了人类,而不是代码生成

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 也就是说,您的示例函数无法说明const的正确性

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 因此,虽然这回答了字面问题,但您可能误解了const正确性是什么,并打算问其他问题 ,我将避免对此进行猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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