[問題] 暫時物件產生的原因

看板C_and_CPP (C/C++)作者 (王大明)時間2年前 (2022/01/10 22:10), 2年前編輯推噓3(304)
留言7則, 2人參與, 2年前最新討論串1/2 (看更多)
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 最近看到一個例子不太懂這是c++的甚麼機制讓他產生暫時物件的 #include <iostream> #include <string> using namespace std; int main(){ pair<const string,int> data = {"123",5}; const pair<string,int> &ref = data; } 我看文章說因為data的first是const可是ref的first沒有const但是編譯器 不會讓他編譯錯誤會產生暫時物件. 1.可是這邊我就不懂了,是甚麼機制讓他產生暫時物件的?有這機制的名稱嗎?? 還有為何不讓他編譯錯誤要幫他產生暫時物件?? 2.這種暫時物件新手蠻容易犯錯的, 有比較好的方式可以幫助我們確認是否產生暫時物件嗎?? 我知道書上推薦用auto不過如果先不考慮auto有甚麼方法確認嗎?? 感謝各位 ※ 編輯: WangDaMing (111.248.244.154 臺灣), 01/10/2022 22:18:42

01/11 06:39, 2年前 , 1F
cppreference 搜 reference_initialization
01/11 06:39, 1F

01/11 06:43, 2年前 , 2F
Otherwise, if the type of target is not same or
01/11 06:43, 2F

01/11 06:43, 2年前 , 3F
derived from T, and target has conversion function
01/11 06:43, 3F

01/11 08:08, 2年前 , 4F

01/11 08:40, 2年前 , 5F
01/11 08:40, 5F

01/11 08:40, 2年前 , 6F
Standardese:
01/11 08:40, 6F

01/11 08:40, 2年前 , 7F
文章代碼(AID): #1Xt3veAj (C_and_CPP)
文章代碼(AID): #1Xt3veAj (C_and_CPP)