I had no clue why this doesn't work. The following Function
is created by placement new. A function is provided that checks whether it should be destructed, and if so, calls its destructor manually.
Here is the testcase where it seems the destructor is never called:
/* Represents a function at runtime */
class Function {
public:
/* Creates an invalid function */
Function():codeptr(0) { }
/* Creates a function with the given code pointer */
Function(void *codeptr):codeptr(codeptr) { }
/* Frees the function machine code */
~Function() {
if(*this) {
/* <- I explicitly put a debug output here! */
destroyLLVMCode(codeptr);
}
}
public:
/* Returns true if the function is valid
* (if the code pointer is non-null)
*/
operator bool() const { return codeptr != 0; }
/* Destroy this function by calling its destructor */
void destroy() { ~Function(); }
private:
void *codeptr;
};
I used this like the following. Cut down the code below to the minimum that still exhibits the problem. In my real program, of course, the memory is allocated in another manner, from an allocator.
#include <new>
#include <cstdlib>
int main() {
void *buffer = std::malloc(sizeof(Function));
Function *f = new (buffer) Function(someExecutableLLVMCode);
/* more code .. register with symbol tables etc.. */
f->destroy();
}
You can see I'm calling the destructor in the line reading ~Function()
. The compiler accepts, but it doesn't end up calling it: I verified it by checking whether it really deletes the LLVM code I gave it (put some code into the destructor before deleting the LLVM code that the codeptr
points to, in case the Function
is valid).
I found out later on what is causing that. Could you please provide me with an explanation?