简体   繁体   中英

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?

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

ps: 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;
};

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

Yes, if the array is of fixed size and not allocated dynamically then the memory will be released in the destructor of MyObject . You might find using std::array is a more convenient way of holding a fixed size array:

#include <array>

struct MyObject {
  std::array<float, 10> array;
};

Also, if you are going to dynamically allocate the memory for MyObject I recommend using a smart pointer like unique_ptr :

#include <memory>

auto my_object = std::unique_ptr<MyObject>(new MyObject);
//auto my_object = std::make_unique<MyObject>(); // C++14

If you want a variable sized, dynamically allocated array I recommend using a vector :

#include <vector>

struct MyObject {
  std::vector<float> array;
};

In which case the memory allocated to the array will be released when the MyObject destructor is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM