2011/7/5 Magnus Müller: > Hi, > > > I recently stumbled across the list initialization feature of C++0x and > tried to use it to initialize references. The > following compiles nicely using gcc (gcc 4.6.1, see the end of the > email for gcc -v): > > -------------------- > int main() > { > int y{}; > int &ref{y}; > } > -------------------- > > If I try to use the same style of initialization for a reference to a > user-defined type, gcc reports an error: > > -------------------- > class Y > { }; > > int main() > { > Y y{}; > Y &ref{y}; > } > -------------------- > > % LANG=C make initialization CXXFLAGS="-std=c++0x -Wall -Wextra" > g++ -std=c++0x -Wall -Wextra initialization.cpp -o initialization > initialization.cpp: In function `int main()': > initialization.cpp:9:13: error: invalid initialization of non-const > reference of type `Y&' from an rvalue of type `<brace-enclosed > initializer list>' initialization.cpp:9:8: warning: unused variable > `ref' [-Wunused-variable] > > > This error message makes sense with a certain interpretation of the > quoted paragraph from §8.5.4 (draft N3126): The most recent publicly available draft is N3242 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf That has been superseded by the FDIS. > [...] if T is a reference to class type or if T is any reference > type and the initializer list has no elements, a prvalue temporary of > the type referenced by T is list-initialized, and the reference is > bound to that temporary. [ Note: As usual, the binding will fail and > the program is ill-formed if the reference type is an lvalue reference > to a non-const type. — end note ] > > I think this applies here for my user-defined type Y. But I am wondering > why the first example compiles. Even if there exists a "constructor" for > integers using references that could produce a temporary, the integer > reference should still produce an error as it would bind to an rvalue. > > > So my question is: Where am I wrong? An int is not a class type and your initializer list does not have no elements, so that paragraph doesn't apply. However, that paragraph has changed in the FDIS: Otherwise, if T is a reference type, a prvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference to a non-const type. —end note ] That would mean both initializations should be rejected, but it seems that GCC doesn't implement that yet. I think that contradicts the resolution of DR 1095 which was voted into the FDIS: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1095 Hmm, I think there might be a defect in the FDIS ...