UFO:Alien Invasion

Development => Coding => Topic started by: Duke on February 03, 2014, 08:38:48 am

Title: memset(*this,0,sizeof....
Post by: Duke on February 03, 2014, 08:38:48 am
Cppcheck complains: ERROR using memset on a class that has virtual functions (or similar).

Imho Cppcheck is wrong here. I don't know much about the internals of a compiler, but imho the compiler should keep the function table (and thus the virtuals) well apart from the instance data.

Can anyboy confirm/disconfirm ?
Title: Re: memset(*this,0,sizeof....
Post by: Mattn on February 03, 2014, 12:36:59 pm
one should not use memset of a class with virtual methods - memset would override the vtable, too.
Title: Re: memset(*this,0,sizeof....
Post by: Duke on February 03, 2014, 02:45:08 pm
then sizeof() must comprise the vtable (or at least a ptr to it). But it doesn't afaik.
Title: Re: memset(*this,0,sizeof....
Post by: Sandro on February 03, 2014, 02:46:17 pm
Or overrun the next object in memory, since vtbl link in some compilers uses negative offsets. And I've did not start talking about multiple inheritance classes ...
Title: Re: memset(*this,0,sizeof....
Post by: Duke on February 03, 2014, 05:37:27 pm
My point is that it simply doesn't make sense to store the vtable ptr with the data.
If the compiler did, an array of 10000 instances of class RainDrop would use up 40k bytes of memory where 4 bytes are enough.

The only exception to that is when you are using RTTI. Then it makes sense. Maybe that's where all the superstition comes from ?
Title: Re: memset(*this,0,sizeof....
Post by: DarkRain on February 03, 2014, 09:51:28 pm
But it does! Where else to store it anyway?

Ultimately it doesn't matter if it makes sense or not (to us), the compiler actually does store the vtable pointer with the data. (hidden class member), so yeah, don't do it.