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

后端 未结 7 1082
粉色の甜心
粉色の甜心 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:03

    Leverage the fact that a static instance is initialised to zero: https://ideone.com/GEFKG0

    template 
    struct clearable
    {
        void clear()
        {
            static T _clear;
            *((T*)this) = _clear;
        };
    };
    
    class test : public clearable
    {
        public:
            int a;
    };
    
    int main()
    {
        test _test;
        _test.a=3;
        _test.clear();
    
        printf("%d", _test.a);
    
        return 0;
    }
    

    However the above will cause the constructor (of the templatised class) to be called a second time.

    For a solution that causes no ctor call this can be used instead: https://ideone.com/qTO6ka

    template 
    struct clearable
    {
        void *cleared;
        clearable():cleared(calloc(sizeof(T), 1)) {}
    
        void clear()
        {
            *((T*)this) = *((T*)cleared);
        };
    };
    

    ...and if you're using C++11 onwards the following can be used: https://ideone.com/S1ae8G

    template 
    struct clearable
    {
        void clear()
        {
            *((T*)this) = {};
        };
    };
    

提交回复
热议问题