首页 > 其他分享 >Placement new for a union of derived classes to populate vtable pointer

Placement new for a union of derived classes to populate vtable pointer

时间:2022-10-23 01:55:24浏览次数:77  
标签:node Placement populate union pointer virtual new type

So i am using a union of, say 10 node types, some of them are derived from a common parent.

The node itself doesn't store any information about its type. It is the tagged union struct that consists of this union and a type field.

I needed this tagged union because i want to allocate a pool once, and reuse it - instead of dynamically allocate a node on the heap.

I have multiple creation methods which will retrieve the next avaiable node, based on the type, it can get the corresponding node from the union, and set some member variables.

This seems to work until I tried to call a virtual method on a node s:

s-> was 0xFFFFFFFFFFFFFFFF.
Then i checked the disassembly, it errors at the line where it cannot get access to an offset.

Then I investigate the node, __vfptr unable to read memory.

Ahha, it is because the virtual table isn't populated!

When do we set the virtual table pointer? It's compiler implementation specific, but normally it is when the constructor is called.

So apparently we need to call the cosntructor here, placement new is what we need - knowing where exactly we want to new the node.

And it all worked!

 

This is sort of a mixed case of OO polymophism and taking advantages of a union of things. We could have included the type in the node itself, so that we can write a series of overloading functions or one function with lots of switch cases to process each node type. There's always this organizational balance between human maintenable code and machine friendly code:

  • Virtual functions make each node class easy to write and read, but virtual calls are not the fastest!
  • Adding the type field and writing function flow can make it faster and slightly smaller in memory, but you need to have the mental concept of a bigger problem domain, not just one node type you are dealing with.

 

https://stackoverflow.com/questions/1031543/what-is-the-full-list-of-actions-performed-by-placement-new-in-c

https://www.learncpp.com/cpp-tutorial/the-virtual-table/

标签:node,Placement,populate,union,pointer,virtual,new,type
From: https://www.cnblogs.com/antai/p/16817768.html

相关文章