1

I was reading this question Does calling a destructor explicitly destroy an object completely? where this situation comes up in code.

Object* aWidget = new Widget(); //allocate and construct
aWidget->~Object();             //destroy and DON'T deallocate

From the answers, I undrestand that the memory region is in fact not deallocated in this situation. My question is (more out of curiosity than anything):

How can I delete the memory pointed to by aWidget after the two lines of code above have executed? I would assume calling delete aWidget; would fail because it would try to run the destructor on an already-destructed object. Could you call free(aWidget) or something like that instead to just target the memory?

Community
  • 1
  • 1
John Humphreys
  • 37,047
  • 37
  • 155
  • 255
  • I'm not certain so I'm posting as a comment, but you may be able to call `operator delete(aWidget)`. I'd be curious to see code that ran into this as a valid use case, though! – Cory Nelson Feb 07 '12 at 17:52
  • @CoryNelson you're right, see my answer. I was typing it as you posted the comment. – Luchian Grigore Feb 07 '12 at 17:57

2 Answers2

3

free would, factually speaking, be my best guess. However I don't think you can do anything without invoking UB. How did you arrive at a requirement to invoke the destructor like that?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

Calling free on an object allocated with new is undefined behavior.

I suggest you keep it simple, and call delete.

However, if you want to do this, you can, in some cases, call delete even if you previously called the destructor explicitly. If you call it explicitly, you can view it as a function. The memory isn't freed, so I'm guessing setting member pointers to NULL after you destroy them would be enough to prevent you from running into any trouble. (because calling delete on a NULL pointer is a no-op).

For example, the following should be ok:

class A
{
public:
    int * x;
    A() 
    { 
        x = new int[10]; 
    }
    ~A() 
    { 
        delete[] x; 
        x = NULL; 
    }
};

int main()
{
    A* a = new A;
    a->~A();
    delete a;
    return 0;
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625