Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually destroy member variables?

Tags:

c++

destructor

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?

like image 562
curiousexplorer Avatar asked Dec 22 '22 03:12

curiousexplorer


2 Answers

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.

like image 76
Jason Avatar answered Dec 23 '22 16:12

Jason


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.

like image 27
Xeo Avatar answered Dec 23 '22 15:12

Xeo