首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问下_declspec(novtable),虚函数调用的有关问题

2013-11-19 
请教下__declspec(novtable),虚函数调用的问题class __declspec(novtable) A { public: A(){} virtual voi

请教下__declspec(novtable),虚函数调用的问题


class __declspec(novtable) A 

public: 
A(){} 
virtual void Test(){} 
virtual void Test2(){} 
};

class __declspec(novtable) B : public A 

public: 
B(){} 
virtual void Test(){} 
virtual void Test3(){Test2();} 
};

int main()
{
B b;
b.Test();
b.Test3(); 

getchar();
return 0;


这段代码会崩溃,类A和B经过__declspec(novtable)修饰后不会产生虚表,也不会初始化虚指针,但main里是通过对象来调用函数,《深度探索C++模型》中说“经一个由class object调用的virtual function,这种操作总是被编译器像对待一般的nonstatic member function一样加以决议”,那就是说跟虚函数虚表没有什么关系,可是为什么还会崩溃呢。如果main里像这样调用
A *pA = new B;
pA->Test();
这样崩溃了还能理解,求大神指点下
[解决办法]
可参考下面的这段关于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).

热点排行