Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I initialize a reference in an initializer list with uniform initialization?

That is, why does this:

struct S {};  struct T {     T(S& s) : s{s} {}      S& s; };  int main() {     S s;     T t{s}; } 

give me a compiler error with GCC 4.7:

test.cpp: In constructor 'T::T(S&)': test.cpp:5:18: error: invalid initialization of non-const reference of type 'S&' from an rvalue of type '<brace-enclosed initializer list>' 

?

To fix the error, I have to change the s{s} to s(s). Doesn't this break the, erm, uniformity of uniform initialization?

EDIT: I tried with clang, and clang accepts it, so perhaps it's a GCC bug?

like image 932
HighCommander4 Avatar asked May 09 '12 03:05

HighCommander4


People also ask

Can a reference be initialized?

A reference to T can be initialized with an object of type T , a function of type T , or an object implicitly convertible to T . Once initialized, a reference cannot be changed to refer to another object.

What is uniform initialization?

Uniform Initialization in C++ The uniform initialization is a feature that permits the usage of a consistent syntax to initialize variables and objects which are ranging from primitive type to aggregates. In other words, it introduces brace-initialization that applies braces ({}) to enclose initializer values.

What is initializer list in C ++ When should we use it?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

Do you need to initialize a list?

As mentioned above, in Python, you can easily add and remove elements from a list, so in most cases, it is not necessary to initialize the list in advance. If you want to initialize a list of any number of elements where all elements are filled with any values, you can use the * operator as follows.


1 Answers

Yes, its a bug. This is something new and was voted in the working paper in February 2012 (link).

Nicol Bolas makes a good point in that gcc is actually the conforming compiler according to the FDIS approved C++11 standard because the changes to the working paper were made after that.

like image 179
Jesse Good Avatar answered Oct 14 '22 15:10

Jesse Good