-2

Please have a look at the following code

#include <iostream>

using namespace std;

class Memory
{
private:
    int *memory;

public:
    Memory()
    {
        memory = new int[3];

        for(int i=0;i<3;i++)
        {
            memory[i] = i;
            cout << memory[i] << endl;
        }
    }

    ~Memory()
    {
        delete[] memory;
    }
};

int main()
{
    cout << "Running" << endl;

    Memory m;
    // do I have to invoke ~Memory() ?

    int *secondMemory = new int[5];
    //How to clear the memory of 'secondMemory' ?

    system("pause");
    return 0;


}

In here, I have cleared the memory of the dynamically allocated memory array in the class's destructor. But my questions are

  1. do I have to invoke ~Memory() ?
  2. How to clear the memory of 'secondMemory' ?

These questions are asked as comments in the appropriate places of the code. Please help!

Edit

The problem here is, if I delete the memory of 'secondMemory' in main(), then the memory is gone as soon as it is allocated!

4

4 Answers 4

11

do I have to invoke ~Memory() ?

No, objects with automatic storage duration (like m) get destroyed when they go out of scope. In other words, the destructor is automatically called by the system. In this case, m gets destroyed upon returning from the main() function.

How to clear the memory of 'secondMemory' ?

Every object allocated with new must be destroyed through a corresponding call to delete, and every array allocated with new[] must be destroyed with a corresponding call to delete[]:

delete[] secondMemory;

Failing to do so results in memory leaks.

However, keep in mind that using raw pointers to perform manual memory management is regarded as a bad programming practice in Modern C++. Rather use standard containers, like std::vector<>, whenever you can.

11
  • ok, but you mean I have to call it just after the memory allocation? I mean, just down the int *secondMemory = new int[5]; ? Then, the memory is allocated, and it is gone within mili seconds!
    – PeakGen
    Apr 5, 2013 at 15:24
  • @Yohan: You have to deallocate the memory before you lose the last reference to it. In this case, you have to delete[] it before you return from main() (but you can do it any time before returning from main()).
    – Andy Prowl
    Apr 5, 2013 at 15:25
  • Btw, this "Modern C++" style thing consists of using RAII, which is a feature that was already in the language in the 1990s. Yes, it's that modern. Apr 5, 2013 at 15:26
  • @Andy I've been seeing a lot of claims that this is a bad practice lately. Do you have a definitive source for that? While I agree that it is overused and most cases could be replaced by a standard container, it is still a fundamental part of C++ memory management in general. I feel, especially for someone just learning the language, they should have a clear understanding of how this works before moving on to containers and other advanced concepts like RAII.
    – Dave Rager
    Apr 5, 2013 at 15:36
  • @DaveRager: I understand what you mean, but I actually see things the other way round. Learners should first get familiar with the higher-level abstractions and concepts that the language and its standard library offer, and only after delve into the low-level details of how those things are implemented, and how to obtain maximum control over memory allocation.
    – Andy Prowl
    Apr 5, 2013 at 15:39
4

do I have to invoke ~Memory()

No, destructors are invoked automatically when the object falls out of scope.

How to clear the memory of 'secondMemory'?

Use delete[] secondMemory;

1
  • -1 for unsafe delete[].
    – Puppy
    Apr 5, 2013 at 15:49
2
 Memory m;
// do I have to invoke ~Memory() ?

No this is not dynamically allocated so the compiler calls the destructor for you when m goes out of scope. In this case when main returns.

int *secondMemory = new int[5];
//How to clear the memory of 'secondMemory' ?

This is allocated dynamically so you have to deallocate it.

delete [] secondMemory;
6
  • -1 for unsafe delete[].
    – Puppy
    Apr 5, 2013 at 15:44
  • @DeadMG How please explain.
    – user995502
    Apr 5, 2013 at 15:45
  • 1
    @DeadMG none of those apply in the example code given. I believe your downvotes are unfair and stating that it is unsafe is misleading.
    – Dave Rager
    Apr 5, 2013 at 16:45
  • 1
    @DeadMG Those points are beyond the scope of this question - it's a shame you downvoted all the answers on that basis.
    – JBentley
    Apr 5, 2013 at 19:19
  • 1
    @DeadMG drawing your sword on a fly here :)
    – user995502
    Apr 5, 2013 at 19:20
2

do I have to invoke ~Memory() ?

When the object goes out of scope, ~Memory() will automatically be invoked. So no, you don't have to do anything to invoke it manually.

How to clear the memory of 'secondMemory' ?

Just use

delete [] secondMemory

since you initialized int* secondMemory using new and [].

1
  • -1 for unsafe delete[].
    – Puppy
    Apr 5, 2013 at 15:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.