Is this C++ structure initialization trick safe?

前端 未结 16 1160
有刺的猬
有刺的猬 2020-12-23 17:56

Instead of having to remember to initialize a simple \'C\' structure, I might derive from it and zero it in the constructor like this:

struct MY_STRUCT
{
            


        
16条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 18:21

    You can simply value-initialize the base, and all its members will be zero'ed out. This is guaranteed

    struct MY_STRUCT
    {
        int n1;
        int n2;
    };
    
    class CMyStruct : public MY_STRUCT
    {
    public:
        CMyStruct():MY_STRUCT() { }
    };
    

    For this to work, there should be no user declared constructor in the base class, like in your example.

    No nasty memset for that. It's not guaranteed that memset works in your code, even though it should work in practice.

提交回复
热议问题