Do I have to manually delete object even after destructor?

1.1k views Asked by At

This question relates to C++ game engine, called AppGameKit (AGK).

I've created a separate class for Text so that I don't have to call AGK functions when creating Text. Here's the simple class:

Text.h

class Text 
{
  private: int _ID;
  void Destory();

  public:
    void AddText();
  Text(int ID);
  ~Text();
};

Text::Destroy() 
{
  agk::DeleteText(_ID);
}

Text::~Text() 
{
  Text::Destroy();
}

Now my question is when I'm calling this class in any other class, say MainMenu, do I have to delete the button in the class MainMenu that I'm creating using this class or will the destructor of Text will automatically get called and delete the button.

MainMenu.cpp

MainMenu::Initilization()
{
        Text * mainText = new Text(1);
}

MainMenu::Destory()
{
       agk::DeleteText(1); // DO I HAVE TO DO THIS?
}

MainMenu::~MainMenu()
{
       MainMenu::Destory(); 
}

AGK function delete is called to delete text so that the memory is deallocated. Similar to C++ delete keyword.

Personally, I think deleting the button in MainMenu class should be unnecessary but I'm confused as to whether the destructor of Text class is even called. Please let me know if you think I'm wrong.

3

There are 3 answers

0
Bathsheba On BEST ANSWER

Every new has to be balanced with a delete else you will leak memory. (You can use classes like std::unique_ptr which will manage the deletion for you but they still call delete under the hood).

Currently, mainText goes out of scope at the end of the Initilization function, so you lose the pointer that you need for a successful delete.

0
Mohit Jain On

Do I have to manually delete object even after destructor?

No.


You called Text * mainText = new Text(1); in Initialization, so call delete mainText in Destroy

When you call delete mainText

  • If mainText is not null its destructor would be called
  • If mainText is not null its memory would be freed

No need to mention, the destructor already calls agk::DeleteText

2
Spanky On

The basic rule of thumb in C++ is for every new() there must be a delete(). This ensures that there would be no memory leakage. In most modern OS, there is no memory leakage ever. Once your program exits, the OS claims back the memory and puts it back in heap. But what happens when your program is running for a long time. This means you will keep leaking memory until your program exits. So it's best to delete the allocated memory and adhere to the rule of thumb.

Hope it helps!!