在C ++中,const引用延长了从函数返回的临时对象的生命周期,这是一个已知特性,但使用常量引用来访问从函数返回的临时对象的成员是否可行呢?
示例:
#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;
}
输出:
123456 = 123456
str
)的生命周期。也就是说,通过复制返回值,你应该没问题。RVO
将避免进行额外的复制。 - Arunmu