Is there a better way to initialise C structures in C++ code?
I can use initialiser lists at the variable declaration point; however, this isn't that useful if all arguments are not known at compile time, or if I'm not declaring a local/global instance, eg:
Legacy C code which declares the struct, and also has API's using it
typedef struct
{
int x, y, z;
} MyStruct;
C++ code using the C library
void doSomething(std::vector<MyStruct> &items)
{
items.push_back(MyStruct(5,rand()%100,items.size()));//doesn't work because there is no such constructor
items.push_back({5,rand()%100,items.size()});//not allowed either
//works, but much more to write...
MyStruct v;
v.x = 5;
v.y = rand()%100;
v.z = items.size();
items.push_back(v);
}
Creating local instances and then setting each member one at a time (myStruct.x = 5;
etc) is a real pain, and somewhat hard to read when trying to add say 20 different items to the container...
Structure members can be initialized using curly braces '{}'.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.
No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).
If you can't add a constructor (which is the best solution in C++03 but you probably have compatibility constraint with C), you can write a function with the same effect:
MyStruct makeAMyStruct(int x, int y, int z)
{
MyStruct result = { x, y, z };
return result;
}
items.push_back(makeAMyStruct(5,rand()%100,items.size()));
Edit: I'd have checked now that C++0X offers something for this precise problem:
items.push_back(MyStruct{5,rand()%100,items.size()});
which is available in g++ 4.4.
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