Offset to complete object from subobject

怎甘沉沦 提交于 2019-12-10 23:10:07

问题


I need to get the front-most address of a complete object even if what I have happens to be a subobject.

The current version of my experimental smart pointer can only compare locations of a complete object and one of it's subobjects. It is simply storing their addresses and their sizes in bytes and see if they overlap. The problem lies in comparing two subobjects of a complete object in the case of multiple inheritance. Since these subobjects will not overlap each other they wont be recognized as belonging to the same object. This would require the offset to the "head" of the complete object from the subobject to gain the address of the complete object for comparison.

Note that this comparison has nothing to do with accessing or destructing the objects. It's only to map handles to an object, no matter what the sub type of the handle is. The handle itself is responsible for holding the type and disposing of it once no more references to the same object exist.

Is it possible to hijack the vtable in order to get the offset to the complete object? I've been unable to find a standard function that allows you to do this. My assumption is that abusing the vtable is highly implementation dependent and will most likely not be reusable on another compiler. Using typeid on an object manages to work out what the complete object is given a subobject, so I believe it's possible to achieve. Too bad it wont return that address...

Just to be clear: I do not need the offset of the subobject inside another object. I need to do it the other way around and find the complete object from the subobject without knowing the complete object's type.


回答1:


dynamic_cast<void*>(myBaseObject);

Doing this will get you a pointer to the most derrived type, i.e. the most complete object. You can do what you like with that once you've got that pointer.



来源:https://stackoverflow.com/questions/8647661/offset-to-complete-object-from-subobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!