开发者

What's the sizeof the virtual function table pointer?

In single inheritances, is the size of a pointer to virtual table always equal to the size of a voi开发者_JS百科d*? Say,

class vft { virtual ~vft(); }
assert (sizeof(vft) == sizeof(void*));

Would that assertion always be true?


No, Virtualism is implementation defined. It is an compiler implementation detail.
So you cannot say that will be true always.

Also, You should refrain yourself from writing any code(like the one in Question) that assumes an detail that is left open by the Standard as an compiler implementation detail, Because that makes your code not 100% portable across compilers & might even fail drastically on some compilers.


The C++ ISO Standard says nothing about virtual function table pointer in the first place. A Compiler may follow this mechanism to support runtime-polymorphism or can come up with any other which doesn't even involve vptr. Its entirely upto the compiler writers. Since the Standard doesn't say anything about vptr, how can it say about its size? No way. The conclusion is: what you're doing (or assuming) isn't gauranteed by the language. However, for a compiler, it might be always true.

As a sidenote, for your compiler, how can you conclude that sizeof(vft) will be equal to sizeof(vptr)? It could very well be that sizeof(vft) > sizeof(vptr). I don't claim that though.


This is implementation-dependent.


"Would that assertion always be true?" Depends on what you mean by "always".

As others have already pointed out, this is an implementation detail that is subject to change even with different versions of the same compiler. The C++ standard says nothing about it, so you can't rely on it.

On the other hand, I've never seen a compiler where this wouldn't be true.


Aside from the facts that everyone else already pointed out, I feel like the standard does give some guarantees. Namely, for class vft { void* a, b; virtual ~vft(); } then sizeof(vft) > sizeof(void*). I'm pretty sure the standard guarantees that much at least, virtual functions or no.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜