开发者

Destructor not called after destroying object placement-new'ed

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 exhibi开发者_Go百科ts 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?


This is because ~Function(); in not a destructor call syntactically here. Use this->~Function(); instead.

~Function(); is parsed as an operator ~ and creation of the Function object on the stack. Function class has an operator bool that's why this will be compiled.


Change your explicit destructor call to

this->~Function();

Currently the ~Function is constructing a "Function" and then calling the ~ bitwise operator, (legal because you have a conversion to bool), and then destructing that, not the called object.


As I recall the destructor cannot be called explicitely. Try moving the cleanup code from destructor to other function and call it instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜