The C++ standard draft N4296 says
[class.temporary/5] The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except...
So I want to know what happens if two or more references are bound to a temporary. Is it specific in the standard? The following code may be an example:
#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;
}
If we change the bounding order, the case is different.
#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;
}
The compilation is done on Ideone.com.
I guess [class.temporary/5] only holds when the first reference is bound to the temporary, but I cannot find an evidence in the standard.
std::string
object created from"hello"
, and it is bound to the first reference variable. The second reference is bound to the lvalue resulting from evaluating the id-expression containing the first variable. – Kerrek SB