Dynamically allocated C ++ object

Hi everyone, I had a quick question. I am returning to C ++ and wondered about this

If I have a dynamically allocated object:

MyObject* obj = new MyObject(); 

And it has an array inside the member:

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

will just do the usual removal:

 delete obj; 

free all memory (including an array) on an object? Or do I need to do something special for this?

+5
source share
2 answers

Yes, you're okay. All object memory will be released.

ps: If you also dynamically create memory inside the class, you must free your memories inside the ~MyObject() destructor.

For instance:

 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: you need an additional instance constructor and a dopi assignment statement to force it to follow a rule of three .

+3
source

Yes, if the array has a fixed size and is not allocated dynamically, then the memory will be released in the MyObject destructor. You may find that using std::array is a more convenient way to store a fixed-size array:

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

In addition, if you are going to dynamically allocate memory for MyObject , I recommend using a smart pointer, such as unique_ptr :

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

If you need a dynamically distributed array with a variable size, I recommend using vector :

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

In this case, the memory allocated for the array will be freed when the MyObject destructor is called.

0
source

Source: https://habr.com/ru/post/1205525/


All Articles