Re: [問題] malloc問題

看板C_and_CPP作者時間15年前 (2009/03/16 22:53), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串6/6 (看更多)
※ 引述《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

03/16 22:57, , 1F
因為 reference 在某些情況可以不使用 pointer
03/16 22:57, 1F

03/16 23:00, , 2F
像是 int a = 0 ; int &refa = a嗎?
03/16 23:00, 2F
文章代碼(AID): #19lcV_CH (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #19lcV_CH (C_and_CPP)