Find out the size of a polymorphic object

南笙酒味 提交于 2019-12-10 12:55:49

问题


I have an pointer Base* base_ptr to an polymorphic object. Is it possible to find out the size of the dynamic type of said object?

AFAIK, sizeof(*base_ptr) yilds the size of the static type of base_ptr. I'm beginning to suspect this isn't possible, but maybe I'm overlooking something.

Note: I'm aware that I could add a virtual function to my type hierarchy which returns the size, but this is not a desirable solution in my case.

EDIT: sizeof(base_ptr) -> sizeof(*base_ptr)


回答1:


No, you can't do that in C++ - at least in a portable way. The best bet would be to have getSize() member function implemented in each class.




回答2:


Yes. You can implement a virtual function in the base class which returns the size:

class Base
{
   virtual int size() { return sizeof(Base); }
};
class Derived : public Base
{
   virtual int size() { return sizeof(Derived); }
};

//......
Base* b = new Derived;
int size = b->size(); //will call Derived::size() and return correct size



回答3:


You can use CRTP idiom, if possible, as I described here: https://stackoverflow.com/a/14730166/908336



来源:https://stackoverflow.com/questions/8122763/find-out-the-size-of-a-polymorphic-object

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