作者elefant ()
看板C_and_CPP
标题Re: [问题] malloc问题
时间Mon Mar 16 22:53:49 2009
※ 引述《littleshan (我要加入剑道社!)》之铭言:
: 推 littleshan:传 reference 效能和 pointer 一样,并不会比较快 03/16 18:13
: 推 chrisdar: 传指标的话 有的时候还要 *p 取值 03/16 18:28
: 传 reference 本质上还是传 pointer 呀
: 只是 dereference 的时候 compiler 帮你做掉了
: 直接来看 assembly 就知道了
: #include <cstdlib>
: void alloc_mem(int** p)
: {
: *p = (int*)malloc(sizeof(int));
: }
: void alloc_mem(int*& p)
: {
: p = (int*)malloc(sizeof(int));
: }
: 使用 gcc 编出的结果:
: _Z9alloc_memRPi: ; alloc_mem(int*&)
: .LFB14:
: pushq %rbx
: .LCFI0:
: movq %rdi, %rbx
: movl $4, %edi
: call malloc
: movq %rax, (%rbx)
: popq %rbx
: ret
: ...
: _Z9alloc_memPPi: ; alloc_mem(int**)
: .LFB13:
: pushq %rbx
: .LCFI1:
: movq %rdi, %rbx
: movl $4, %edi
: call malloc
: movq %rax, (%rbx)
: popq %rbx
: ret
: 两边的 assembly 完全相同。
从上面gcc编译出来的assembly看来
即使参数列上是reference
compiler还是会在函式呼叫点
先对(int*)取址然後push到stack
所以牵扯到一个pointer的copy
但
http://en.wikipedia.org/wiki/Reference_(C%2B%2B) 提到
"It is unspecified whether or not a reference requires storage."
这样意思是不是说
reference的实作方法是compiler dependent呢?
有没有可能其他compiler编出来的assembly,是在函式里对参数"直接存取"?
谢谢喔~
------
自己想了一下,如果函式不是inline的话
好像几乎不可能不配置记忆体耶?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 203.70.99.75
1F:→ HudsonE:因为 reference 在某些情况可以不使用 pointer 03/16 22:57
2F:→ elefant:像是 int a = 0 ; int &refa = a吗? 03/16 23:00