开发者

When are C++ destructors explicitly called?

What are the instances where you need to expli开发者_JAVA百科citly call a destructor?


When you use placement-new is a common reason (the only reason?):

struct foo {};

void* memoryLocation = ::operator new(sizeof(foo));
foo* f = new (memoryLocation) foo(); // note: not safe, doesn't handle exceptions

// ...

f->~foo();
::operator delete(memoryLocation);

This is mostly present in allocators (used by containers), in the construct and destroy functions, respectively.

Otherwise, don't. Stack-allocations will be done automatically, as it will when you delete pointers. (Use smart pointers!)

Well, I suppose that makes one more reason: When you want undefined behavior. Then feel free to call it as many times as you want... :)


No. You never need to explicitly call a destructor (except with placement new).

(shameless C++ FAQ Lite plug ;>)

On an extended note, calling destructors is a guarantee of the compiler -- by using new in a targeted allocation, you break that guarantee -- what is definitively a dangerous thing. If you need special allocation, it's usually better to write custom allocators and/or override new/delete.

Also take note, that calling a destructor explicitly can have extreme complications, and shouldn't be done in any other case than the case mentioned above.


Destructor are called automatically for objects of auto storage type when the object leaves scope and destructor for objects on the heap are called when the delete operator is used on them.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜