Decent way to disallow virtual functions due to placement new usage

Viewed 844

What would be a decent approach to check at compile/run-time that a particular struct/class does not have any virtual functions. This check is required in order to ensure the proper byte alignment when doing placement new.

Having so much as a single virtual function will shift the entire data by a vtable pointer size, which will completely mess things up in conjunction with the placement new operator.


Some more details: I need something that works across all major compiler and platforms, e.g. VS2005, VC++10, GCC 4.5, and Sun Studio 12.1 on top of Windows, Linux, and Solaris.

Something that is guaranteed to work with the following scenario should suffice:

struct A { char c; void m(); };
struct B : A { void m(); };

Should someone decide to make this change:

struct A { char c; virtual void m(); };
struct B : A { void m(); };

It would be great to see a compile-time error that says struct A must not contain virtual functions.

6 Answers
Related