Hello, everyone. It has been a while since my last post.
While watching CppCon 2014 I found this little gem being described by Scott Meyers.
Consider the following code:
decltype(auto) foo() { static int Foo; return Foo; } decltype(auto) bar() { static int Bar; return (Bar); } int main() { decltype(auto) a = foo(); decltype(auto) b = bar(); a++; b++; cout << foo() << ", " << bar() << endl; } |
Would you expect this to print 0, 0? Well, not so fast. decltype(auto) is just a nicer syntax for decltype(name), where name is “unparenthesized id-expression or an unparenthesized class member access”, as described here. Therefore it follows the same rules.
That’s another corner case to remember, but I guess it could also make a nifty party trick, if one can find the right party.
What matters in this case is that Bar is a lvalue if you used:
return (static_cast<int>(Bar));
you would have ended up w/ the result you expected, see it live: http://melpon.org/wandbox/permlink/qknNBHKbHecHt8E0
For reference see this: http://stackoverflow.com/a/24122429/1708801
That’s interesting. Thank you for the comment.
That being said, the SO answer doesn’t say what’s supposed to happen for prvalues (which is the case here, I believe).