Re: [問題] 參數傳指標還是傳reference

看板C_and_CPP (C/C++)作者 (←這人是超級笨蛋)時間13年前 (2012/08/25 08:13), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《sorryChen (陳揚和)》之銘言:

08/23 16:34,
這是 design choice, 合理使用才重要
08/23 16:34

08/23 17:19,
傳指標的優點是 user code 會像這樣 API_x(&val);
08/23 17:19

08/23 17:20,
這樣的 API_x 八成會修改 val
08/23 17:20

08/23 17:21,
如果用 ref 的話 user code 比較不易分辨
08/23 17:21

08/23 17:22,
我自己的選擇是API要改值就用指標,其他都用 ref
08/23 17:22

08/23 17:27,
改值與否應該可以用參數是否加 const 來強調?
08/23 17:27

08/23 17:29,
指標多出的功能就是NULL與否,除此我覺得就是5樓說的
08/23 17:29

08/23 18:02,
我指的是 user code
08/23 18:02
我的習慣也是這樣(從 Qt Style 偷來的) http://doc.qt.nokia.com/qq/qq13-apis.html#pointersorreferences Most C++ books recommend references whenever possible, according to the general perception that references are "safer and nicer" than pointers. In contrast, at Trolltech, we tend to prefer pointers because they make the user code more readable. Compare: color.getHsv(&h, &s, &v); color.getHsv(h, s, v); Only the first line makes it clear that there's a high probability that h, s, and v will be modified by the function call. 我自己是只在傳入不需修改內容值(沒有副作用) 但傳值又比較浪費資源(例如必須傳一整個物件進去)時 才會使用參考作為函式傳入值 -- ╱ ̄ ̄ ̄╲ ▏◢█◣ 成龍表示: 是喔... ′/ ‵ ╰╯ ψQSWEET █◤ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.243.36.234

08/26 02:29, , 1F
推這個style
08/26 02:29, 1F
文章代碼(AID): #1GE1YjVq (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1GE1YjVq (C_and_CPP)