crawfordr4
crawfordr4

Reputation: 157

Struct object destructor

If I were to define a struct like so:

struct info{
   std::string name;
}

and create a new instance of said struct on the heap via:

info* i = new info();

Is the destructor for string called automatically upon calling delete on info, such that any internally allocated memory by the name object is freed? Is this behavior that should be avoided in C++?

Thanks

Upvotes: 2

Views: 524

Answers (2)

The Apache
The Apache

Reputation: 1074

Yes, the destructor is called automatically once delete is called for info. But this doesn't mean that all the internal memory will be freed. There are exceptions here.

Consider a case

struct info
{
  char *name;
}

and in the main code

int main()
{
  info *n =  new info; 
  n->name = new char;

  delete n;
}

In this case, the memory for name will not be freed and you will have a memory leak.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117981

As linked in the comments by @Joachim Pileborg

Destruction sequence
For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.

So to answer your question, yes the destructor for name will be called after the body of the destructor for info is called.

Upvotes: 0

Related Questions