Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ arrow type yields lvalue

According to the C++ Primer, C++ arrow operator yields an lvalue. Additionally decltype of an expression which yields an lvalue will result in a reference type. So why the following decltype does not result in a reference type.

struct MyStruct {
   string name
};
MyStruct s;
s.name = "aname";
MyStruct* p = &s;
decltype (p -> name) str = s.name; //type of str will be string and not &string although p -> name yields an lvalue
like image 668
Nami Avatar asked May 11 '16 15:05

Nami


1 Answers

From cppreference

If the argument is an unparenthesized id-expression or an unparenthesized class member access, then decltype yields the type of the entity named by this expression. If there is no such entity, or if the argument names a set of overloaded functions, the program is ill-formed.

This is the case in your example, so it will return the underlying type of the member, which is a std::string.

If you want, you can add parenthesis so that decltype results in a reference:

//'str' is a std::string&
decltype((p->name)) str = s.name;
like image 100
Rakete1111 Avatar answered Sep 22 '22 20:09

Rakete1111