I have been researching, and nothing relevant has come up, so I came here.
I am trying to avoid memory leaks, so I am wondering:
Say I have class MyClass
with member int
s a
and b
, and an int array c
, which are filled in a member function:
class MyClass
{
public:
int a, b;
int c[2];
void setVariables()
{
a, b = 0;
for (int i = 0; i < 2; i++)
{
c[i] = 3;
}
}
};
int main(int argc, char* argv[])
{
MyClass* mc = new MyClass();
mc->setVariables();
delete mc;
}
Now, after I call delete mc
, will a
, b
, and all the contents of c
be deleted as well? Or will I have to do that explicitly in the destructor of MyClass
?
delete
will reclaim the memory that your object contains. If your type maintains pointers to dynamically allocated memory then you will need to clean those up inside of your destructor.As for your specific quesiton:
They will be cleaned up for you as they were not allocated dynamically.
Variables inside of a class have class scope and are destroyed when the class is. The only thing you need to worry about is pointers -- those will need to be addressed appropriately in your destructor.
For your specific example, the answer is yes. That's because you allocated the member variables on the stack. If you had used
new
to allocate memory for the member variables the answer would be no and would require you to explicitly delete the member variables in the class' destructor.Your three variables were not allocated with
new
so there would be no need to delete them at all.They would be destructed when your class is
delete
d (as they were allocated when your class wasnew
d), but that's not the same as being deleted.Class members are a part of the class' memory structure.
So when you free that memory, the members are freed with it.
NOTE:
If you have pointers they are destroyed too, BUT the memory they point at isn't destroyed.
More about class memory consumption:
C++ Classes
The rule is very simple: every object created with
new
must be destroyed exactly once withdelete
; every array created withnew[]
must be destroyed exactly once withdelete[]
; everything else must not be deleted. So your code is correct; you are deletingmc
after creating it withnew
, and not deleting the members which were not created withnew
.Applying the rule can be quite tricky when the program flow gets complicated (especially when exceptions are involved); for that reason, it is much better not to delete objects yourself, but to immediately use the result of
new
to initialise a smart pointer to manage the object for you.