#include <iostream>
#include <typeinfo>
class A {};
A f() { return A(); }
int main() {
auto &&a = f();
std::cout << typeid(f()).name() << std::endl;
std::cout << typeid(a).name() << std::endl;
std::cout << typeid(A{}).name() << std::endl;
return 0;
}
It outputs
1A
1A
1A
Questions are,
- what does
1A
mean here? (GCC on a linux box) auto &&
should be a forwarding reference, and in this case sincef()
returns anA
object by value,a
should be deduced to rvalue reference, correct?- If
a
is indeed rvalue reference, and since a (temporary) rvalue's lifetime could only be extended by a const lvalue ref,a
should go out of scope right after this line, is that correct?
Edit: Fixed the most vexing problem in the last cout
statement, as many pointed out.
Summary of the great answers, for posterity:
1A
is internal representation of typeA
, by Guillaume Racicot. AndF1AvE
indicates a Function style cast in typeid(A()) resulting in a prvalue, by Ted Lyngmo.- turns out
typeid()
is not the tool to check reference, as it gives the referenced end type. Ted Lyngmo gave the right way to do it, and yes it is an r-value reference.
static_assert(std::is_rvalue_reference_v<decltype(a)>); // like this, ...
static_assert(std::is_same_v<decltype(a), A&&>); // or like this
- Richard Critten gave the link that says "The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11)...".