Joh*_*itb 13 c++ destructor placement-new
我不知道为什么这不起作用.以下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;
};
Run Code Online (Sandbox Code Playgroud)
我用这个如下.将下面的代码减少到仍然存在问题的最小值.当然,在我的真实程序中,内存是从分配器以另一种方式分配的.
#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();
}
Run Code Online (Sandbox Code Playgroud)
你可以看到我在行阅读中调用析构函数~Function().编译器接受,但它并没有最终调用它:我验证它通过检查其是否真的删除LLVM代码,我把它(把一些代码放入析构函数删除LLVM代码的前codeptr点,万一Function是有效).
我后来发现了导致这种情况的原因.你能帮我解释一下吗?
Kir*_*sky 24
这是因为~Function();在这里没有语法上的析构函数调用.请this->~Function();改用.
~Function();被解析为运算符~并Function在堆栈上创建对象.Functionclass有operator bool这就是为什么要编译它.
将显式析构函数调用更改为
this->~Function();
Run Code Online (Sandbox Code Playgroud)
目前〜函数正在构造一个"函数",然后调用〜按位运算符(合法,因为你转换为bool),然后破坏它,而不是被调用的对象.