baibaichen wrote:
I test the following codes in VC++ and GCC
const std::string& str = "";
std::cout << typeid(str).name() << std::endl;
std::cout << typeid(const std::string&).name()<< std::endl;
std::cout << typeid(const std::string).name()<< std::endl;
Both think str, const std::string& and const std::string are the same
type!
Aren't str and const std::string& reference type?
'const std::string&' is a reference type. As for 'str', it gets more
complicated. 'str' _itself_ is a reference, no argument about it.
However, 'str' as an C++ _expression_ has type 'const std::string'. No
reference in it.
The point his that 'typeid' in C++ works with the type of the
_expression_ supplied as an argument. Now, in C++ expressions never
really have reference type, in a sense that whenever you have an
expression that is supposed to evaluate to a value of type 'T&', the
resultant type is immediately adjusted to 'T' (as an lvalue, see 5/6).
I.e. when it comes to expression results, reference type is very
short-lived, it decays from 'T&' to 'T' so quickly, that you never
really get a chance to see that 'T&'. That is exactly what happens in
your code.