Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Proper Structure Initialization

Tags:

c++

c++11

Having a structure like this in C++11:

struct von
{
    std::string Name;
    unsigned int ID;
    std::vector<std::string> Checks;
};

Should it be initialized like this:

    von v = {"",0,{}};

Or like this:

    von v = {};

Both ways seem to work, but the compiler warns about -Wmissing-field-initializers on the latter example.

Edit:
Here are my compiler options:

g++ main.cpp -ansi -Wall -Wextra -Weffc++ -std=c++0x

I'm using g++ (Debian 4.6.2-12) 4.6.2

like image 213
01100110 Avatar asked Mar 04 '12 18:03

01100110


People also ask

How do you initialize a structure in C?

Generally, the initialization of the structure variable is done after the structure declaration. Just after structure declaration put the braces (i.e. {}) and inside it an equal sign (=) followed by the values must be in the order of members specified also each value must be separated by commas.

How do you initialize a new struct?

myStruct = (MyStruct*)calloc(1, sizeof(MyStruct)); should initialize all the values to zero, as does: myStruct = new MyStruct(); However, when the struct is initialized in the second way, Valgrind later complains "conditional jump or move depends on uninitialised value(s)" when those variables are used.

How do you initialize the structure of a element?

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.

How do we initialise a structure give an example?

Initializing structure members struct car { char name[100]; float price; }; //car1 name as "xyz" //price as 987432.50 struct car car1 ={"xyz", 987432.50};


1 Answers

This doesn't require initializer_list at all and work perfectly fine with C++03. Edit: (Ok, for the initialization of the vector you need C++11) In a struct or array initialization, all not explicitly given values are zero-initialized, so if that's what you want = {}; will work just fine.

like image 130
cooky451 Avatar answered Oct 22 '22 04:10

cooky451