我完全不知道为什么这个代码不起作用。下面的Function
是通过placement new创建的。提供了一个函数来检查是否需要销毁它,如果需要,则手动调用其析构函数。
以下是测试用例,其中似乎从未调用析构函数:
/* 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;
};
我像下面这样使用它。将以下代码削减到最小,仍然展示问题。在我的真实程序中,当然,内存是从分配器以另一种方式分配的。
#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();
}
你可以看到我在代码行中调用了析构函数~Function()
。虽然编译器接受,但实际上它并没有被调用:我通过检查编译器是否确实删除了我提供的LLVM代码(在删除codeptr
指向的LLVM代码之前,在析构函数中放入了一些代码,以防Function
是有效的)来验证这一点。后来我发现了原因。你能向我解释一下吗?