[問題] const reference是什麼?

看板C_and_CPP作者 (JOMI)時間7年前 (2018/07/13 18:22), 7年前編輯推噓1(1016)
留言17則, 5人參與, 7年前最新討論串1/1
看到一篇文章 https://www.fluentcpp.com/2018/07/13/the-incredible-const-reference-that-isnt- const/ 我覺得蠻有趣的 其中一段提到 The get() method returns a const T&, with T coming from template T. In our sec ond case, T is int&, so const T& is const (int&) & 這邊。const (int&) & 為什麼他可以直接看出這const 是修飾reference (int&) & const 然後就是這邊感覺多了一個& 也許他這段有解釋 So being氲onst氽oesn’t say much for a reference, since they always乸re氲onst, since they cannot rebind. This implies that氲onst (int&)湶s effectively the s ame type as湶nt&. 但實在看不是很懂 這邊能不能套用forwarding reference的規則 int& & collapse成 int&, 所以變成 int & const ,我不確定,而且覺得不能這樣想 而且正常試圖寫 https://ideone.com/95tBGJ 無法寫得出這個語意. 請問各位有什麼規則需要釐清的嗎 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.8.199.223 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1531477341.A.D50.html ※ 編輯: lovejomi (39.8.199.223), 07/13/2018 18:26:31 ※ 編輯: lovejomi (39.8.199.223), 07/13/2018 18:35:48

07/13 18:58, 7年前 , 1F
So being氲onst氽oesn’t say much for a reference,
07/13 18:58, 1F

07/13 18:59, 7年前 , 2F
since they always乸re氲onst, since they cannot reb
07/13 18:59, 2F

07/13 18:59, 7年前 , 3F
這種語言我也看不懂
07/13 18:59, 3F

07/13 19:23, 7年前 , 4F
So being const doesn’t say much for a reference, s
07/13 19:23, 4F

07/13 19:23, 7年前 , 5F
ince they always are const, since they cannot rebin
07/13 19:23, 5F

07/13 19:23, 7年前 , 6F
d. This implies that const (int&) is effectively th
07/13 19:23, 6F

07/13 19:23, 7年前 , 7F
e same type as int&.
07/13 19:23, 7F

07/13 19:23, 7年前 , 8F
大概是這樣?
07/13 19:23, 8F

07/13 21:42, 7年前 , 9F
亂碼那段是說這件事 https://tinyurl.com/y8gkkcng
07/13 21:42, 9F

07/13 21:44, 7年前 , 10F
他是一層一層把語意消掉,T& const 等價於 T&
07/13 21:44, 10F

07/13 21:45, 7年前 , 11F
而 (T&)& 等價於 T&,所以得到 (T&) const & 等價於T&
07/13 21:45, 11F

07/13 23:41, 7年前 , 12F
我也不知道為什麼手機貼上都正確 送出就變亂碼...moptt
07/13 23:41, 12F

07/13 23:44, 7年前 , 13F
所以簡單講就是int&& collapse 成int&, 然後int&const沒
07/13 23:44, 13F

07/13 23:44, 7年前 , 14F
意義,所以const直接忽略?
07/13 23:44, 14F

07/14 00:17, 7年前 , 15F
const (int&) & =>const 修飾 (int &) =>reference自帶
07/14 00:17, 15F

07/14 00:17, 7年前 , 16F
const語意,去掉const =>int & & =>做collapse=>int &(
07/14 00:17, 16F

07/14 00:17, 7年前 , 17F
相當於 int const *) 我感覺是這樣
07/14 00:17, 17F
文章代碼(AID): #1RI7rTrG (C_and_CPP)