c++filt does not demangle typeid name
Asked Answered
R

2

10

I am running a code on GCC C++ compiler, to output the 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';
   }

but I get the following results:

P6Circle
P8triangle

and on demangling,

./shape | c++filt  

I get the same output as earlier. Any other solution?

Rejoin answered 25/9, 2013 at 13:4 Comment(2)
Name mangling for types is not that complicated, and surely not in that case... I don't know what the answer to your question is, but a workaround is reading the type yourself. P pointer to 6Circle Circle object (the 6 is the length of the name)... P pointer to 8triangle triangle (8 characters).Telesthesia
Hmm, that is simple. Thanks but just wanted to know if there is a cleaner way of getting the sameRejoin
I
19

You need to use c++filt -t for types so the following should work:

./shape | c++filt -t

the man page for c++filt says the following for -t:

Attempt to demangle types as well as function names. This is disabled by default since mangled types are normally only used internally in the compiler, and they can be confused with non-mangled names. For example, a function called "a" treated as a mangled type name would be demangled to "signed char".

Inquisitorial answered 25/9, 2013 at 13:6 Comment(0)
A
2

Which version of GCC (and its corresponding libstdc++) are you using?

With GCC 4.8, I have

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);
}

and then I can use

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

where ptr points to some object with an RTTI (i.e. with some virtual methods, notably a virtual destructor).

Anguished answered 25/9, 2013 at 13:8 Comment(2)
Then you should upgrade to GCC 4.8.1 because typeid is better implemented there.Anguished
Congratulations, you've just induced hundreds of people to add memory leaks into their apps. You must deallocate the buffer returned by abi::__cxa_dmangle after creating the return string.Selfassurance

© 2022 - 2024 — McMap. All rights reserved.