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

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

    You can use pointer arithmetic to find the range of bytes you want to zero out:

    class Thing {
    public:
        Thing() {
            memset(&data1, 0, (char*)&lastdata - (char*)&data1 + sizeof(lastdata));
        }
    private:
        int data1;
        int data2;
        int data3;
        // ...
        int lastdata;
    };
    

    (Edit: I originally used offsetof() for this, but a comment pointed out that this is only supposed to work on PODs, and then I realised that you can just use the member addresses directly.)

    0 讨论(0)
提交回复
热议问题