Delete Operator

Hey guys. Recently I added a line of code in my class destructor that deletes a window object that was declared as a pointer. It looked like this.

1
2
3
Class::~Class() {
    delete window;
}


This didn't work. All it did was cause an assertion error. Can anyone explain to me why this doesn't work?

Note: The window object is redeclared inside of most classes and the original object is passed via pointers through the constructor of most object. The one I'm deleting isn't the original object.
Then you are deleting memory that the class "logically" doesn't own.

If your class does this:
 
window = new Window();  //Then you need to delete it 


However, if it is done like this, which is the way you describe it.
1
2
3
4
Class(Window * pWindow) : window(pWindow)
{}

//Then no, you do not want to delete it... 


The use of pointers does not mean that you have to delete/free memory. You only delete/free memory that you allocate, declaring a pointer is no different than any other variable.

There are other subtleties I've left out
Last edited on
Does this fall under the second category you described?

1
2
3
4
5
6
7
8
class A {
public:
    Window *window;

    A(Window *_window) {
        window = _window;
    }
};


Also, does this kind pointer need to have a try-catch block around it?
Also, does this kind pointer need to have a try-catch block around it?


No. All this code is saying is point window to the same memory location that already exists and is pointed to by _window.

It is up to you to handle the case where the pointer is null.
Topic archived. No new replies allowed.