Proper usage of initializer

Hi all,

here's what I have:
1
2
3
4
struct foo {
	int i;
	std::vector<int> ints;
};


Here's what I'm going to do with that:
1
2
3
4
    std::vector<foo> foos;
    
    foos.push_back({1});  // feels wrong
    foos.push_back({2, std::vector<int>()});  // feels meh 


Here's the thing:
I'm unsure about foo::ints. Is the std::vector initialized properly when I do {1} (version 1), or is it better to use version 2 where I call the constructor explicitly?

Some background: by the time I add the entry to foos I don't have any data to initialize the vector. It's filled later.
Last edited on
Is the std::vector initialized properly when I do {1} (version 1)

Yes.

is it better to use version 2 where I call the constructor explicitly?

No, I don't think so. But some compilers can warn about this. GCC has the compiler flag -Wmissing-field-initializers (enabled by -Wextra).

 
foos.push_back({1});  // warning: missing initializer for member ‘foo::ints’ 

So as an alternative you might want to use:

 
foos.push_back({3, {}});

https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmissing-field-initializers
So as an alternative you might want to use:
foos.push_back({3, {}});

I tried this earlier and was expecting a raging compiler reaching out of the screen strangling me, because that looks kinda mean.
Like: *beep* you compiler, you'll figure it out.

I guess I'll use that though, at least it shows that it's an initializer for a struct.
Topic archived. No new replies allowed.