c++ - Uniform initialization of references -
i trying understand new uniform initialization of c++0x. unfortunately, stumpled on using uniform initialization of references. example:
int main() { int a; int &ref{a}; }
this example works fine:
% lang=c g++ uniform_init_of_ref.cpp -std=c++0x -o uni -wall -wextra uniform_init_of_ref.cpp: in function `int main()': uniform_init_of_ref.cpp:3:10: warning: unused variable `ref' [-wunused-variable]
(update comeau throws error example, maybe gcc shouldn't compile well)
now, if use custom data type instead of integer, doesn't work anymore:
class y {}; int main() { y y; y &ref{y}; } % lang=c g++ initialization.cpp -std=c++0x -o initialization -wall -wextra initialization.cpp: in function `int main()': initialization.cpp:9:13: error: invalid initialization of non-const reference of type `y&' rvalue of type `<brace-enclosed initializer list>' initialization.cpp:9:8: warning: unused variable `ref' [-wunused-variable]
unfortunately, didn't find relevant section in standard draft. guess misunderstanding usage of uniform initialization, comeau complains message:
comeautest.c(9): error: reference variable "ref" requires initializer y &ref{y};
so, can of point me in right direction?
in case want know why question relevant , why don't use y &ref(y)
: i'd able use uniform initialization in initialization list of constructor:
class x { }; class y { const x& x; public: y (const x& xx): x{xx} {} }; int main () { x x; y y{x}; }
this fails same error message above.
note:
- i using
lang=c
enable english error messages. - gcc version: 4.6.1
according n2672 paragraph 8.5.4.4 should say:
otherwise, if t reference type, rvalue temporary of type referenced t list-initialized, , reference bound temporary. [ note: usual, binding fail , program ill-formed if reference type lvalue reference non-const type. ]
which (if understand correctly) means uniform initialization of references binds them new anonymous instances, seems me it's pretty useless. still not explain why 1 works , other not; should behave same (unless y
has explicit constructors).
Comments
Post a Comment