I have a question about a destructor’s implementation for a class. I understand the right way is using the ~ operator, but take a look at the following code:
class foo
{
private:
int* abc;
public:
foo()
{
abc = new int(2);
}
~foo()
{
delete abc;
}
void func()
{
delete abc;
}
}
Now let us say that the main function is defined as below:
int main(int argc, char** argv)
{
foo a;
a.func();
}
Upon the function call of func() in main, does this work in the exact same way as the destructor? What is the difference between the destructor and this function in any similar setting?
func()and~foo()do the exact same thing. And that’s the problem. Whenagoes out of scope, its destructor~foo()will automatically be called, resulting inabcbeing deleted twice. One way to get around it would be to setabctoNULLat the end offunc()after thedelete, so that when the destructor gets called itdeletes aNULLpointer, which is a special case in C++ where nothing is actually done and is a valid operation.Or, of course, the code could be rewritten in a way that actually made sense and accomplished something.
And just to be really clear, the “difference” between
func()and~foo()is how/when they’re called, not in what they do.func()is manually called by the user, while~foo()is automatically called when the variable goes out of scope.func()may be called zero or more times (it’s up to the programmer), but the compiler will call~foo()exactly once (no more, no less) in this code.