关于 __declspec(novtable) 的使用原则

__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)关键字的类.还有只要在最终的派生类中不要加上此关键字即可,这样就可以安全的使用由最终派生类产生的各种基类的指针和引用了.

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值