看板 C_and_CPP 關於我們 聯絡資訊
開發平台(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
g0010726: cppreference 搜 reference_initialization 01/11 06:39
g0010726: Otherwise, if the type of target is not same or 01/11 06:43
g0010726: derived from T, and target has conversion function 01/11 06:43
Dracarys: https://godbolt.org/z/q39sGv6fe 01/11 08:08
Dracarys: 一樓講的: https://i.imgur.com/VdhI9NT.png 01/11 08:40
Dracarys: Standardese: 01/11 08:40
Dracarys: https://eel.is/c++draft/dcl.init.ref#5.3 01/11 08:40