How to do the equivalent of memset(this, …) without clobbering the vtbl?

后端 未结 7 1097
粉色の甜心
粉色の甜心 2020-11-29 10:39

I know that memset is frowned upon for class initialization. For example, something like the following:

class X { public: 
X() { memset( this,          


        
7条回答
  •  鱼传尺愫
    2020-11-29 11:07

    This is hideous, but you could overload operator new/delete for these objects (or in a common base class), and have the implementation provide zero'd out buffers. Something like this :

    class HideousBaseClass
    {
    public:
        void* operator new( size_t nSize )
        {
            void* p = malloc( nSize );
            memset( p, 0, nSize );
            return p;
        }
        void operator delete( void* p )
        {
            if( p )
                free( p );
        }
    };
    

    One could also override the global new/delete operators, but this could have negative perf implications.

    Edit: I just realized that this approach won't work for stack allocated objects.

提交回复
热议问题