How to unmangle mangled names of C++ lambdas?

后端 未结 4 1357
你的背包
你的背包 2021-01-01 17:13

After compilation with g++-4.9.3 -std=c++11 the code

#include 
#include 
using namespace std;
int main() { cout          


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 18:10

    You can use GCC's special abi::__cxa_demangle function:

    #include 
    #include 
    #include 
    #include 
    
    // delete malloc'd memory
    struct malloc_deleter
    {
        void operator()(void* p) const { std::free(p); }
    };
    
    // custom smart pointer for c-style strings allocated with std::malloc
    using cstring_uptr = std::unique_ptr;
    
    int main()
    {
        // special function to de-mangle names
        int error;
        cstring_uptr name(abi::__cxa_demangle(typeid([]{}).name(), 0, 0, &error));
    
        if(!error)
            std::cout << name.get() << '\n';
        else if(error == -1)
            std::cerr << "memory allocation failed" << '\n';
        else if(error == -2)
            std::cerr << "not a valid mangled name" << '\n';
        else if(error == -3)
            std::cerr << "bad argument" << '\n';
    }
    

    Output:

    main::{lambda()#1}
    

    According to The Documentation this function returns a c-style zero-terminated string allocated using std::malloc which the caller needs to free using std::free. This example uses a smart pointer to free the returned string automatically at the end of the scope.

提交回复
热议问题