How to properly deallocate variables in deconstructor

Let's suppose I've to create a class with this structure

 class A
 {
     int a;
     B* b;
 }

I read that it's a good thing deallocate the variable used in the deconstructor.

~A
{
   delete b;
}

but how I have to do for a variable of type int, double, primitive type in general? What's the best way or a good programming rule?


You don't need to delete basic types.

But not just for basic types. For anything that you didn't allocate with new you don't have to call delete on. Even for pointers.


In c++ for every new there should be a delete .

When new is called you are allocating on the heap and you are responsible for deallocating it. If no new is used, the memory is allocated on the stack and will be deallocated upon going our of scope.

Please read this and this. There are plenty of information on this topic.


I assume that B is another class. You just declared the pointer. But not instantiated yet. You have not allocated any memory to that pointer.So initialize it to null.

 B* b = NULL;

Now before deleting it in the deconstructor check whether you have allocated any memory or not.

if(b){delete b; b = NULL;}

In the above code if you allocate any memory then only it will deallocate. for eg: if you did

*b = new b

now some memory is allocated for this particular pointer. So it will deallocate properly. You don't need to deallocate unless until you allocate some memory to pointer. Hope this will help you.

链接地址: http://www.djcxy.com/p/79804.html

上一篇: 堆栈中的对象与C ++中的堆中的对象

下一篇: 如何在解构器中正确释放变量