C++filt 不会取消类型标识名称

c++filt does not demangle typeid name

本文关键字:标识 类型 取消 C++filt      更新时间:2023-10-16

我正在GCC C++编译器上运行代码,以输出type_info::name:

#include <iostream>
#include <typeinfo>
using namespace std;
class shape {
   protected:
   int color;
   public:
   virtual void draw() = 0;
   };

class Circle: public shape {
   protected:
   int color;
   public:
   Circle(int a = 0): color(a) {};
   void draw();
   };
   void Circle::draw() {
   cout<<"color: "<<color<<'n';
   }
class triangle: public shape {
   protected:
   int color;
   public:
   triangle(int a = 0): color(a) {};
   void draw();
   };
   void triangle::draw() {
   cout<<"color: "<<color<<'n';
   }
int main() {
   Circle* a;
   triangle* b;
   cout<<typeid(a).name()<<'n';
   cout<<typeid(b).name()<<'n';
   }

但我得到以下结果:

P6Circle
P8triangle

在拆解时,

./shape | c++filt  

我得到的输出与之前相同。还有其他解决方案吗?

您需要

对类型使用 c++filt -t,因此以下内容应该有效:

./shape | c++filt -t

C++filt 的手册页对 -t 说:

尝试对类型和函数名称进行解散。 默认情况下禁用此功能,因为重整类型通常仅在编译器内部使用,并且它们可能会与非重整名称混淆。 例如,将名为"a"的函数视为损坏的类型名称将被拆解为"有符号字符"。

您使用的是哪个版本的 GCC(及其相应的 libstdc++)?

使用 GCC 4.8,我有

static inline std::string 
 demangled_type_info_name(const std::type_info&ti)
{
  int status = 0;
  return abi::__cxa_demangle(ti.name(),0,0,&status);
}

然后我可以使用

std::cout << demangled_type_info_name(typeid(*ptr)) << std::endl;

其中ptr指向具有RTTI的某个对象(即使用某些虚拟方法,特别是虚拟析构函数)。