Re: [Dev-C++] Stress with structs and pointers.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <or...@vp...> - 2003-06-12 19:16:13
|
Per Westermark wrote:
> memset() works very well in C programs. However, there are some
> things to remember about memset() on structures.
>
> If the code is later moved to C++, and the struct gets virtual methods,
> the memset() code will be deadly, since it will clear the address of the
> virtual method table (VMT), which will make calls to the methods kill the
> program. Also, the VMT is normally used for run-time type checking, such
> as dynamic cast.
>
> One more thing about memset() of structures is that in C++, the struct may
> contain members that are themself classes with a constructor. The work
> done by these constructors will be overwritten.
>
> Memset of structures that are part of a multiple-inherritance aggregate is
> also dangerous, since it kills the hidden fields the compiler added to
> safely locate the addresses of the different base classes.
Thanks for this info, I didn't know about this :)
Indeed is useful.
But, as a last note, if you (the original asker) use PURE C only, then
you can safely use memset().
But if you are in the C++ world, you should rarely use the standard C
library anyway (where memset() is for example).
> Note that most of the time, it is enough to just write:
>
> struct mystruct s = {0};
>
> and then the compiler will assign zero to all members of the structure.
> This kind of initialization is directly portable to c++ without any
> dangerous side effects.
Are you sure, this works 100% in just C? I don't know, that's why I ask.
What happens, when I have a struct with 5 elements, and I write:
struct mystruct s = {0,0,0}; /* 3 only */
How many will be initialised?
Thanks in advance.
--
Greetings,
Balázs
|