据已知特征的C++,一个常量引用延伸从函数返回的临时对象的生命时间,但是它可以接受使用恒定的参考到临时对象的成员从函数返回?
例:
#include <string>
std::pair<std::string, int> getPair(int n)
{
return {std::to_string(n), n};
}
int main(int, char*[])
{
const int x = 123456;
const auto& str = getPair(x).first;
printf("%d = %s\n", x, str.c_str());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
123456 = 123456
Run Code Online (Sandbox Code Playgroud)