Jellicle
Jellicle

Reputation: 30206

C++ destructor for object containing object containing pointer

I could use some clarification on destructors.

I understand that if an object contains a pointer to allocated memory, then the object's destructor should call delete on that pointer. But what if an object contains an object that contains a pointer to allocated memory, such as a string?:

class Foo
{
    string bar;
};

Foo* foo = new Foo;
delete foo;

Is there aught I must do to ensure that the underlying char[] in the string is deallocated?

Upvotes: 1

Views: 456

Answers (4)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

When your class is destructed, all its members - including the string - are also automatically destructed.

Cleaning up any internal resources held by the string (of which the char array is an implementation detail that no other class should rely on) is the string object's destructor's responsibility.

Upvotes: 2

doron
doron

Reputation: 28872

You can look at the rule as follow. Any object you create (and retain ownership of) with new must be destructed by calling delete in the destructor.

Upvotes: 1

Praetorian
Praetorian

Reputation: 109079

The string type's destructor is responsible for cleaning up any resource it owns. Your object's destructor will call the destructors of member objects.

Upvotes: 2

Brian Neal
Brian Neal

Reputation: 32379

The string class destructor is responsible for any cleanup. You don't have to worry about it.

Upvotes: 2

Related Questions