-2

I have the following C++ class:

class DEF
{
   //...
}

class ABC
{
   public:
      DEF my_def;
      ~ABC();
   //...
}

And somewhere:

ABC* abc = new ABC(...);
delete abc;

My question:

Will my_def be accessible after calling delete abc? Is it safe to do abc->my_def.somefunc() after the delete? -

今天春天
  • 941
  • 1
  • 13
  • 27

1 Answers1

4

No, after abc's destructor ran, its members will be destroyed in reverse order of their declaration. When abc is deleted, all its memory is free'd. That includes my_def in your example.

Maybe this question will be useful to you: What is a smart pointer and when should I use one?

Addendum: One major problem with C++ is undefined behavior. Programming errors such as use-after-free may appear to work 80% of the time, if the memory was not reused in the meantime. But chances are that you overwrite unrelated memory and/or allow reading foreign data. That is a severe security problem, and a crashing program is the best you can hope for at this point.

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • @今天春天, you are mistaking C++ for a memory managed language such as Java or Python. Please read the answer in the linked question and look up any concept you don't understand. – Kijewski Apr 18 '16 at 21:07