0

When I put delete in the destructor of my class, the system crashes when I exit the program.

For example I use wxWidgets radiobutton:

wxRadioButton *rb1;

I initialize it this way in the constructor of my class:

rb1 = new wxRadioButton(this, ID_RADIOBUTTON_1, _T("&Bied"), wxPoint(310,40), wxSize(110,20),wxRB_GROUP);

and I delete in the destructor of that class:

  if (rb1) delete rb1;

but it crashes every time, I have to put it on comment so it won't crash, (but I know its not the right way to deal with it).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
IonOne
  • 385
  • 4
  • 15
  • 2
    The `if` is not helping at all. – Elazar Sep 30 '13 at 18:18
  • 1
    Could it be that you are copying instances of your class and you haven't written a copy constructor and assignment operator? – juanchopanza Sep 30 '13 at 18:18
  • Let me guess ... you haven't defined a copy constructor and/or assignment operator for your class. Please read [this](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – Praetorian Sep 30 '13 at 18:19
  • 3
    If you simply want it created by the constructor and destroyed by the destructor, why mess around with `new` at all? Just make it a member. – Mike Seymour Sep 30 '13 at 18:20
  • (If you do need dynamic allocation for some reason, use smart pointers. If you don't want to do that for some reason, remember the [Rule of Three](http://stackoverflow.com/questions/4172722)). – Mike Seymour Sep 30 '13 at 18:22
  • 2
    Reading this, you aren't suppose to call delete in wxWidgets: http://wiki.wxwidgets.org/Avoiding_Memory_Leaks#The_wxWidgets-specific_part UI frameworks tend to do this, make sure you follow their guidelines carefully. – GManNickG Sep 30 '13 at 18:28
  • @GManNickG : in the wiki, is it said that you need to delete objects on the heap and that's what i have here i think – IonOne Oct 01 '13 at 11:20
  • @IonOne: From the page: "This is done with the `Destroy()`-method of wxWindow. Instead of using `delete`, you must use `myWindow->Destroy()`, which will wait until next idle loop and then do something like delete `myWindow;`." – GManNickG Oct 01 '13 at 15:35

1 Answers1

1

Are you sure you're not deleting the pointer twice? Doing so could result in nasty crashes.

Alternatively, simply switch to using a member variable instead, so you won't have to deal with the allocation and deallocation.

Community
  • 1
  • 1
AbdullahC
  • 6,649
  • 3
  • 27
  • 43