Is it possible to redefine destructor?

2019-08-31 10:51发布

I've encountered a problem with "redefineing" destructor. The thing is I have been given a definition of struct that i cannot modify. It is a "leaf" of a tree. Goal is to free only a part of the tree while returning a pointer to the remaining subtree. My idea is to use reference counting. This is the given code:

struct TLeaf {
   TLeaf* m_L;
   TLeaf* m_R;
   ~TLeaf(void) {
     delete m_L;
     delete m_R;
   }
}

Is there at least way to avoid calling this destructor? Actually any idea is acceptable. :D

Thank you very much good people of Stack Overflow. :)

标签: c++
2条回答
Explosion°爆炸
2楼-- · 2019-08-31 11:24

You could nullptr out the values before you delete the node. delete ptr where ptr is nullptr is safe and does nothing

TLeaf* ltmp = node->m_L;
TLeaf* rtmp = node->m_R;

node->m_L = nullptr;
node->m_R = nullptr;

delete node;

// now use ltmp and rtmp as you need
查看更多
一夜七次
3楼-- · 2019-08-31 11:27

Since you cannot modify the TLeaf, what you can do is to modify the user code.

0) If you are using heap allocation, try operator delete(p) instead of delete p.

1) If you are using stack allocation, avoid directly using the type TLeaf:

char leaf[sizeof(TLeaf)];
new (leaf) TLeaf(...); // placement new
查看更多
登录 后发表回答