This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| Clearing Constructors Submitted by

I was looking at the tip of the day section, and I found one were it was warning about using memset in the constructors. The tip is title is: How To Not Overwrite Your vTable, by Jaap Suter: There he mentions to stay away from memsets in the constructors. In general I agree with him, but there are cases where there are just way too many variables to keep tack of, although that could be argue that something when wrong somewhere else. it is a fact of life that it happens. Worse yet, if there is not a form of auto clear the variables at some point you will forget to clear one. This type of bug is worse than the one that Jaap Suter found, because it will work some times.
Here is a bit of code that could help finish with these type of problems.

    #include <stdlib.h
    #include <string.h
    #include <stdio.h
    #include <assert.h

    #define zeroclass(PTR,TYPE)                                                         \
    {                                                                                   \
        int Error_Different_Types[ sizeof(*(PTR)) == sizeof(TYPE) ]={0};                \
        struct zeroclass_bigger_ : public TYPE { virtual zeroclass_muchbigger(){} };    \
        if( sizeof(zeroclass_bigger_)  sizeof(TYPE) ) memset( (PTR), 0, sizeof(TYPE) );\
        else            memset( (((void**)(PTR))+1), 0, sizeof(TYPE)-sizeof(void*) );   \
    }

    struct pepe
    {
        int Count;

        pepe::pepe( void )
        {
            zeroclass( this, pepe );
        }

        void Alive( void )
        {
            printf( "(Normal)I am alive[%d]!!!\n", Count);
        }

    };

    struct pepe2
    {
        int Count;

        pepe2::pepe2( void )
        {
            zeroclass( this, pepe2 );
        }

        virtual void Alive( void )
        {
            printf( "(Virtual)I am alive[%d]!!!\n", Count);
        }
    };

    void main( void )
    {
        pepe  P1;
        pepe2 P2;

        P1.Alive();
        P2.Alive();

        // Also can be use like this
        zeroclass( &P1, pepe  );
        zeroclass( &P2, pepe2 );

        P1.Alive();
        P2.Alive();
    }

Tomas Arce
www.zen-x.net

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.