How to apply sizeof() operator to non-static class member methods?

做~自己de王妃 提交于 2019-12-02 05:33:31

You cannot obtain the size of a member-function, but you can obtain the sizeof a pointer-to-member-function:

int size = sizeof( &MyClass::foo );

The same goes for non-member functions (and static member functions), the size of the function cannot be obtained. It might be misleading because in most contexts, the name of the function decays automatically into a pointer to the function basically in the same way that an array decays to a pointer to the first element, but as in the case of arrays, sizeof does not trigger the decay and that in turn means that you have to ask for the pointer explicitly.

iirc this would return size of function pointer anyways, so why do that? Or am I mistaken?

Edit: I was mistaken, this is invalid code, event if function were out of class. All you can do with sizeof and function is get size of function pointer(which you need to make first). If you want to get size occupied by function code you'll need some other way to get that.

Some further reading: http://msdn.microsoft.com/en-us/library/4s7x1k91(v=vs.71).aspx

Use

sizeof(int (MyClass::*)())

since you're taking the "size of a member function pointer of MyClass that returns int and takes no arguments".

Wanted to know if we can at all find the sizeof() a member method.

No, because the C++ language doesn't have such a concept. Or the size of any kind of function.

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