Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this considered an extended initializer list?

#include <vector>

struct foo {
    int i;
    int j;
    int k;
};

int main() {
    std::vector<foo> v(1);
    v[0] = {0, 0, 0};
    return 0;
}

When compiling this using g++, I get the following warning:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]

As far as I can tell, though, it's just a normal initializer list. The struct is a POD type.

Is this a bug or am I missing something?

like image 576
someguy Avatar asked Oct 28 '11 14:10

someguy


People also ask

Why do we use initializer list?

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.

How do initializer lists work?

An initializer list starts after the constructor name and its parameters. The list begins with a colon ( : ) and is followed by the list of variables that are to be initialized – all of​ the variables are separated by a comma with their values in curly brackets.

When should a constructor use an initializer?

Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

What is STD initializer list?

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .


2 Answers

Pre C++11 (and possibly C99) you can only initialize a POD at creation, not at arbitrary runtime points, which is what you're attempting here (assignment from an initializer list).

You can make a null_foo though:

int main()
{
    const foo null_foo = {0, 0, 0};
    std::vector<foo> v(1);
    v[0] = null_foo;
    return 0;
}
like image 120
Mark B Avatar answered Nov 07 '22 17:11

Mark B


Brace-initialization for aggregates is only valid during declaration-initialization:

Foo a = { 1, 2, 3 };

It is not a way to generate temporaries midway: some_function(true, {1,2,3}, 'c').

C++11 adds uniform initialization in which you can indeed write f(Foo{1,2,3});.

like image 25
Kerrek SB Avatar answered Nov 07 '22 17:11

Kerrek SB