5

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?

1
  • 2
    Yes, it will. Arrays are no different to other built-in types in this respect. Commented Oct 26, 2014 at 1:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@juanchopanza What do you mean by break (after fixing all syntax issues)?
See the Rule of Three. Imagine what will happen if you copy this class.
-1 for example of int* test, this is a bad idea. Use a container that manages its own memory.
@MattMcNabb Using int *test is just for an illustration of how to manage dynamically-created memory in class.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.