views:

93

answers:

1

Is the following code legal?

std::string&& x = "hello world";

g++ 4.5.0 compiles this code without any problems.

+4  A: 

This is discussed on usenet currently. See Rvalue reference example in 8.5/3 correct or wrong?.

It's not legal.

Johannes Schaub - litb
@Jerry that is a subbullet of "the reference shall be an rvalue reference and the initializer expression shall be an rvalue", which the string-literal does not satisfy.
Johannes Schaub - litb
@Jerry string literals are lvalues, like in C. See 5.1.1/1. Unlike plain ints, they refer to objects and need to convert to pointers. Thus, they indeed have the property of being an "storage locator value" (which lvalues that refer to objects are).
Johannes Schaub - litb
@Johannes: Yup -- I hadn't found 5.1.1/1, which clearly does say so. Thanks. That clearly makes the interpretation impossible.
Jerry Coffin
I believe that they could also be rvalues, technically. But being an lvalue, i think, does fit more because it indicates the referred storage is static, instead of temporary. In C89, non-lvalue array expressions couldn't convert to pointers, so there the reason was very technical in nature. C99 lifts that restriction.
Johannes Schaub - litb
"It's not legal." -> Do you think this could still change during the standardization process? Because I'd really like it to be legal :)
FredOverflow
@Fred i've no idea :(
Johannes Schaub - litb
Does the sad smiley imply that you would also like my example to be legal?
FredOverflow
@Fred i don't really know. I've got too little experience with rvalue references to make a founded opinion. :(
Johannes Schaub - litb
Wait a minute, do you seriously expect me to believe you have never written a move constructor or something? ;)
FredOverflow