GotW #88: A Candidate For the “Most Important const” – Sutter’s Mill
The Lifetime of A Temporary and Its Extension: Explained | YY++.io
正确
返回”abc“的时候,会生成一个临时对象,也就是返回了一个右值
// Example 1
string f() { return "abc"; }
void g() {
const string& s = f();
cout << s << endl; // can we still use the "temporary" object?
}
string foo() {
return string("123");
};
int main() {
const string& val = foo();
printf("%s\n", val.c_str());
return 0;
}
错误
// Example 2
string f() { return "abc"; }
void g() {
string& s = f(); // still legal?
cout << s << endl;
}