Why does calloc require two parameters and malloc just one?

前端 未结 5 1887
礼貌的吻别
礼貌的吻别 2020-12-09 09:39

It\'s very bothersome for me to write calloc(1, sizeof(MyStruct)) all the time. I don\'t want to use an idea like wrapping this method and etc. I mean I want to

5条回答
  •  借酒劲吻你
    2020-12-09 10:12

    You shouldn't allocate objects with calloc (or malloc or anything like that). Even though calloc zero-initializes it, the object is still hasn't been constructed as far as C++ is concerned. Use constructors for that:

    class MyClass
    {
    private:
        short m_a;
        int m_b;
        long m_c;
        float m_d;
    
    public:
        MyClass() : m_a(0), m_b(0), m_c(0), m_d(0.0) {}
    };
    

    And then instantiate it with new (or on the stack if you can):

    MyClass* mc = new MyClass();
    

提交回复
热议问题