I have the following code (works only on gcc):
#include <iostream>
#include <cstdlib>
#include <string>
#include <typeinfo>
#include <cxxabi.h>
const std::string demangle (const char* name) {
int status = -4;
char* res = abi::__cxa_demangle(name, 0, 0, &status);
const char* const demangled_name = (status == 0) ? res : name;
std::string ret_val(demangled_name);
std::free(res);
return ret_val;
}
template <typename T>
const std::string getname (T x)
{
return demangle(typeid(x).name());
}
int main()
{
std::add_const<int>::type *p = static_cast<const int *>(0);
std::cout << getname(*p) << std::endl;
}
On my local computer (with gcc 4.7.0(experimental) it crashes (run with gdb gives a segfault). However, with ideone.com, it prints “int” as expected. Heres, a link to the example. Also, getting rid of the template and calling demangle(typeid(x).name()) directly fixes the problem, so what is wrong with the template?
EDIT
I forgot to include the type_traits header (doh!) which fixed the problem, however I would still like to know what is going on a little better.
pis a null pointer, and dereferencing it (i.e*p) invokes give undefined behaviour (UB). You are lucky that it gives segfault. And since it is actually UB, all compilers (and all versions) may not give segfault, for that is what UB means, i.e anything could happen.Why don’t you try this instead: