__declspec(novtable)
MSDN的解释是
"
This is a __declspec extended attribute.
This form of __declspec can be applied to any class declaration, but should only be applied to pure interface classes, that is, classes that will never be instantiated on their own. The __declspec stops the compiler from generating code to initialize the vfptr in the constructor(s) and destructor of the class. In many cases, this removes the only references to the vtable that are associated with the class and, thus, the linker will remove it. Using this form of __declspec can result in a significant reduction in code size.
If you attempt to instantiate a class marked with novtable and then access a class member, you will receive an access violation (AV).
"
意思大概就是说这个关键字只应该用在纯虚类中,也就是说用了这个关键字的类不应该被实例化,当实例化了有这个关键字修饰的类的成员时将会发生访问违例(因为虚表的值未知)
基本意思是讲清了,但到底什么时候应该用呢?难道只有纯虚类才可以有这个关键字吗?看看 ATL里有多少非纯虚类都有这个关键字修饰呢,一般化情况下使用了此关键字的类,一般化不要实例化,如果实例化 必须保证不使用 this指针(包括引用)来调用成员函数(特别要注册成员函数内互相调用也是通过this指针实现的),否则结果未知.
要想安全的使用这个关键字,最好不要去实例化任何一个使用了__declspec(novtable)关键字的类.还有只要在最终的派生类中不要加上此关键字即可,这样就可以安全的使用由最终派生类产生的各种基类的指针和引用了.