首页 > 解决方案 > 如何动态转换没有虚拟方法的类的指针?

问题描述

我正在使用llvm库,我想检查 llvm::Value * 是否实际上是 llvm::LoadInst *(llvm::LoadInst 是从 llvm::Value 继承的)。

但遗憾的是,llvm::Value 不包含任何虚拟方法!(是的,即使没有虚拟析构函数)是否可以dynamic_cast在没有虚拟方法的类上使用,或者有没有其他方法来进行类型检查?

标签: c++oopllvm

解决方案


在 LLVM 中,有一个llvm::dyn_cast<T>将使用 LLVM 的内部构造从一种类型动态转换为另一种类型,只要它们确实是有效的转换 - 如果您使用错误的 type T,它将返回 a nullptr

所以像:

llvm::Value *v = ... some code here ... 
...
llvm::LoadInst* li = llvm::dyn_cast<llvm::LoadInst>(v);
if (!li) { ... not a LoadInst, do whatever you should do here ... }
else { ... use li ... }

自然,如果您已经知道这v是 a LoadInst,则无需检查 - 但assert(li && "Expected a LoadInst");如果您弄错了, an 会发现。

请注意,您不要像使用C++ 标准那样使用T*for 。llvm::dyn_cast<T>dynamic_cast

代码中的这条注释llvm::Value解释了没有 vtable 正是因为这个原因(http://www.llvm.org/doxygen/Value_8h_source.html#l00207

   /// Value's destructor should be virtual by design, but that would require
   /// that Value and all of its subclasses have a vtable that effectively
   /// duplicates the information in the value ID. As a size optimization, the
   /// destructor has been protected, and the caller should manually call
   /// deleteValue.
   ~Value(); // Use deleteValue() to delete a generic Value.

推荐阅读