Is this C++ structure initialization trick safe?

前端 未结 16 1187
有刺的猬
有刺的猬 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条回答
  •  猫巷女王i
    2020-12-23 18:41

    Try this - overload new.

    EDIT: I should add - This is safe because the memory is zeroed before any constructors are called. Big flaw - only works if object is dynamically allocated.

    struct MY_STRUCT
    {
        int n1;
        int n2;
    };
    
    class CMyStruct : public MY_STRUCT
    {
    public:
        CMyStruct()
        {
            // whatever
        }
        void* new(size_t size)
        {
            // dangerous
            return memset(malloc(size),0,size);
            // better
            if (void *p = malloc(size))
            {
                return (memset(p, 0, size));
            }
            else
            {
                throw bad_alloc();
            }
        }
        void delete(void *p, size_t size)
        {
            free(p);
        }
    
    };
    

提交回复
热议问题