Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocated object C++

Hey everyone I got a quick question. I'm getting back into C++ and was wondering about this

If I have dynamically allocated object:

MyObject* obj = new MyObject();

And it has an array inside as member:

class MyObject 
{
public:
   MyObject();
   ~MyObject();
   float array[16];
   private:
};

will just doing a normal delete:

delete obj;

on the object free up all the memory (including the array)? Or do I need to do something special for that?

like image 539
CatfishAlpha45 Avatar asked Oct 20 '22 23:10

CatfishAlpha45


1 Answers

Yes, you're doing fine. All the memory of the object will be released.

p.s.: If you also dynamically create memory inside the class, you should release their memories inside the destructor ~MyObject().

For example:

class MyObject
{
public:
    /** Constructor */
    MyObject() : test(new int[100]) {}
    /** Destructor */
    ~MyObject() { delete []test; };  // release memory in destructor 
    /** Copy Constructor */
    MyObject(const MyObject &other) : test(new int[100]){
        memcpy(test, other.test, 100*sizeof(int));
    }
    /** Copy Assignment Operator */
    MyObject& operator= (MyObject other){
        memcpy(test, other.test, 100 * sizeof(int));
        return *this;
    }

private:
    int *test;
};

p.s.2: Extra copy constructor and dopy assignment operator are needed to make it follow Rule of three.

like image 172
herohuyongtao Avatar answered Oct 22 '22 12:10

herohuyongtao