Reputation: 23
I know that destructor is used to destroy global pointers in a class but do i need them to destroy normal variables like int or std::string?
how about array like int num[2]?
what variable types should be destroyed in destructor?
for example:
class myclass
{
public:
myclass()
~myclass()
{
delete num;
delete ar_num;
delete str;
}
private:
int num;
std::string str;
int ar_num[2] = {0,1};
}
Upvotes: 0
Views: 2256
Reputation: 5409
There are some variables which are assigned memory on process stack. So, as soon the process exits, the stack will automatically clean the memory occupied. You only need to delete
the variables for whom you have allocated memory by new
.
You can see this as the malloc
ing in C
. You only need to free
the memory dynamically allocated on your request.
Upvotes: 0
Reputation: 154007
Everything should be destructed in the destructor, but...
All direct members will be destructed automatically; you cannot
have a destructor which doesn't destruct them. (In some cases,
like int
, the "destructor" is in fact a no-op.)
You're confusing destruction and deletion. You only delete
things which have been dynamically allocated. (Directy—if
you do new MyClass
, num
will be dynamically allocated as
part of MyClass
. But you shouldn't, and indeed you cannot
delete it.) The argument of delete
must be a pointer, and it
must point to something that was created using new
.
Upvotes: 1
Reputation: 409384
You should only delete
what you new
. Since you don't allocate the member variables yourself, you should not (and as none of the variables are pointers, you can't) free them with delete
.
Rule of thumb: If you do new
then you need to do delete
.
Upvotes: 8