C struct as class member variable, zero "init" data in class constructor
Hello,
So, at my work we use a static analysis tool and it is pointing out some uninitialized variables. One of which is a class member variable which is a C struct. Now, that variable is already declared in the header file for the class.
Currently in the class constructor I am doing:
Code:
memset( &thestruct, 0, sizeof( thestruct ) );
Is there a C++ way to do this? I Googled this but all I really found was:
Code:
StructDef thestruct = {};
Which doesn't really apply here. Thanks.
Re: C struct as class member variable, zero "init" data in class constructor
In C++ you usually implement a (default and probably some other) ctor(s) in your structure and do the default and other initialization within the ctor(s)
Re: C struct as class member variable, zero "init" data in class constructor
True, but I am dealing with a C struct and so wasn't quite sure.
Re: C struct as class member variable, zero "init" data in class constructor
Are you compiling the file as a 'C' file or a 'C++' file?
Viggy
Re: C struct as class member variable, zero "init" data in class constructor
I'd have to say C++ because we use both C and C++ files when we build the executable.
Re: C struct as class member variable, zero "init" data in class constructor
Try adding a constructor to the struct. If you compile with C++ the compilation will succeed but in C it will not.
Re: C struct as class member variable, zero "init" data in class constructor
Quote:
Originally Posted by
Alterah
Is there a C++ way to do this? I Googled this but all I really found was:
Code:
StructDef thestruct = {};
Which doesn't really apply here. Thanks.
In an initializer list, you could use a function that returns an initialized instance of the struct. Something like
Code:
template <class T>
T MakeZeroInstance()
{
T t = {};
return t;
}
MyClass::MyClass()
: myStruct(MakeZeroInstance<MyStruct>())
{
}
Re: C struct as class member variable, zero "init" data in class constructor
you don't need to write a ctor, just use value-initialization that for a C-struct implies zero-initialization:
Code:
struct A{ /* ... */ };
struct B{ A a; B():a(){} }; // a is zero-initialized, eg: a's scalar members are set to zero