为什么我们不通过引用在函数中传递POD? [英] Why do we not pass POD by reference in functions?
本文介绍了为什么我们不通过引用在函数中传递POD?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直被告知我们不应该通过引用传递POD。但最近我发现一个引用实际上根本没有内存。
I've always been told that we should not pass POD by reference. But recently I've discovered that a reference actually takes no memory at all.
那么为什么我们选择写:
So why do we choose to write:
void DoSomething(int iNumber);
而不是:
void DoSomething(const int& riNumber);
是不是更有效率?
推荐答案
实际上在这种情况下(使用int)传递值可能更有效,因为只需要1次内存读取而不是2,访问传递的值。
Actually in this case (using int) passing by value is probably more efficient, since only 1 memory-read is needed instead of 2, to access the passed value.
示例(使用-O2优化):
Example (optimized using -O2):
int gl = 0;
void f1(int i)
{
gl = i + 1;
}
void f2(const int& r)
{
gl = r + 1;
}
int main()
{
f1(1);
f2(1);
}
Asm
.file "main.cpp"
.text
.p2align 2,,3
.globl __Z2f1i
.def __Z2f1i; .scl 2; .type 32; .endef
__Z2f1i:
LFB0:
pushl %ebp
LCFI0:
movl %esp, %ebp
LCFI1:
movl 8(%ebp), %eax
incl %eax
movl %eax, _gl
leave
ret
LFE0:
.p2align 2,,3
.globl __Z2f2RKi
.def __Z2f2RKi; .scl 2; .type 32; .endef
__Z2f2RKi:
LFB1:
pushl %ebp
LCFI2:
movl %esp, %ebp
LCFI3:
movl 8(%ebp), %eax
movl (%eax), %eax
incl %eax
movl %eax, _gl
leave
ret
LFE1:
.def ___main; .scl 2; .type 32; .endef
.p2align 2,,3
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
LFB2:
pushl %ebp
LCFI4:
movl %esp, %ebp
LCFI5:
andl $-16, %esp
LCFI6:
call ___main
movl $2, _gl
xorl %eax, %eax
leave
ret
LFE2:
.globl _gl
.bss
.align 4
_gl:
.space 4
这篇关于为什么我们不通过引用在函数中传递POD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文