curiousexplorer
curiousexplorer

Reputation: 1237

How to manually destroy member variables?

I have a basic question on destructors.

Suppose I have the following class

class A
{
public:

int z;
int* ptr;

A(){z=5 ; ptr = new int[3]; } ;
~A() {delete[] ptr;};

}

Now destructors are supposed to destroy an instantiation of an object. The destructor above does exactly that, in freeing the dynamically alloctaed memory allocated by new.

But what about the variable z? How should I manually destroy it / free the memory allocated by z? Does it get destroyed automatically when the class goes out of scope?

Upvotes: 5

Views: 7654

Answers (5)

Jason
Jason

Reputation: 32490

It gets "destroyed" automatically, although since in your example int z is a POD-type, there is no explicit destructor ... the memory is simply reclaimed. Otherwise, if there was a destructor for the object, it would be called to properly clean-up the resources of that non-static data member after the body of the destructor for the main class A had completed, but not exited.

Upvotes: 5

Xeo
Xeo

Reputation: 131789

z is automatically destroyed. This happens for every "automatic" variable. Even for pointers like int*, float*, some_class*, etc. However, when raw pointers are destroyed, they are not automatically deleted. That's how smart pointers behave.

Because of that property, one should always use smart pointers to express ownership semantics. They also don't need any special mentioning in the copy / move constructor / assignment operator, most of the time you don't even need to write them when using smart pointers, as they do all that's needed by themselves.

Upvotes: 4

hypercode
hypercode

Reputation: 488

For PODS (plain old data types) like ints, floats and so on, they are automatically destroyed. If you have objects as data members (e.g. std::string aStr;), their destructors will be automatically called. You only have to manually handle memory freeing (like above) or any other manual object or data cleanup (like closing files, freeing resources and so on).

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308111

Destroying an object will destroy all the member variables of that object too. You only need to delete the pointer because destroying a pointer doesn't do anything - in particular it doesn't destroy the object that the pointer points to or free its memory.

Upvotes: 2

sblom
sblom

Reputation: 27343

It does, in fact, get automatically destroyed when the class goes out of scope. A very good way to guess if that's the case is that there's no * after its declaration.

Upvotes: 0

Related Questions