#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?
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.
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.
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.
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 .
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;
}
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});
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With