[问题] 暂时物件产生的原因

楼主: WangDaMing (王大明)   2022-01-10 22:10:46
开发平台(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 (Kevin)   2022-01-11 06:39:00
cppreference 搜 reference_initializationOtherwise, if the type of target is not same orderived from T, and target has conversion function
作者: Dracarys (MayShowGunMore)   2022-01-11 08:08:00

Links booklink

Contact Us: admin [ a t ] ucptt.com