Reputation: 542
struct OBJECT
{
unsigned int Var1;
std::string Str1;
...
bool YesNo;
};
OBJECT Obj[ 327 ];
I am confused about how to zero-out Obj. It has several different type of elements. Do I have to set all of its member to 0?
Like... Obj[0].Str = "";
? So the question is, what is the proper way of doing it?
My attempt:
::memset( &Obj, 0, sizeof( Obj ) );
I am not sure if I am doing it correctly...
Oh and are there any faster way to zero-out an array?
Upvotes: 1
Views: 2240
Reputation: 4207
You should change your declaration to
struct OBJECT
{
unsigned int Var1;
std::string Str1;
...
bool YesNo;
OBJECT()
: Var1()
, Str1()
, ...
, YesNo(false)
{
// Do Nothing
}
};
The array - which you should use over std::array
or std::vector
- will initialise the objects.
Upvotes: 1
Reputation: 74018
Don't do it this way, because you have non trivial members in your struct (e.g. std::string
). You can do this if all your members are only simple data types, like int
, char
, double
or pointers.
The correct way for this type of struct is to define a constructor, which initializes all members properly
struct OBJECT {
OBJECT() : Var1(0), YesNo(false), ... {}
unsigned int Var1;
std::string Str1;
...
bool YesNo;
};
Upvotes: 10
Reputation: 105876
Either provide a custom default constructor or use the compiler defined default constructor:
std::fill(std::begin(Obj), std::end(Obj), OBJECT());
Note that the fill
approach fill only work if you use the default constructor.
Upvotes: 3
Reputation: 37122
The "correct" way is to add a constructor method for your struct that initialises any member variables that don't have constructors of their own, e.g.:
OBJECT_STRUCT()
: Var1(0)
, YesNo(false)
{
}
In that example you'll note that Str1
was not initialised; this is because std::string
has its own constructor that initialises it.
Upvotes: 3