根据C++标准草案N4296
[class.temporary/5] 第二种情况是当一个引用被绑定到一个临时对象上。引用所绑定的临时对象或者引用所绑定子对象的完整对象会在引用存在期间一直持续存在,除非...
我想知道如果有两个或更多的引用被绑定到同一个临时对象上会发生什么。这是否在标准中有具体规定?以下代码可能是一个例子:
#include <iostream> //std::cout
#include <string> //std::string
const std::string &f() {
const std::string &s = "hello";
static const std::string &ss = s;
return ss;
}
int main() {
const std::string &rcs = f();
std::cout << rcs; //empty output
//the lifetime of the temporary is the same as that of s
return 0;
}
如果我们改变边界顺序,情况就不同了。
#include <iostream> //std::cout
#include <string> //std::string
const std::string &f() {
static const std::string &ss = "hello";
const std::string &s = ss;
return ss;
}
int main() {
const std::string &rcs = f();
std::cout << rcs; //output "hello"
//the lifetime of the temporary is the same as that of ss
return 0;
}
编译完成于Ideone.com。
我猜想[class.temporary/5]只有在第一个引用被绑定到临时变量时才有效,但我在标准中找不到证据。
std::string
对象,并且它被绑定到第一个引用变量上。第二个引用被绑定到评估包含第一个变量的id表达式所产生的左值上。 - Kerrek SB