如何解开C ++ lambdas的名称? [英] How to unmangle mangled names of C++ lambdas?

查看:329
本文介绍了如何解开C ++ lambdas的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 g ++ - 4.9.3 -std = c ++ 11 编译

#include <iostream>
#include <typeinfo>
using namespace std;
int main() { cout << typeid([]{}).name() << endl; }

输出 Z4mainEUlvE _ Linux x86_64上的给定lambda。但是, c ++ filt 工具无法取消它。它只是输出给它的输入, Z4mainEUlvE _

outputs Z4mainEUlvE_ as the mangled name of the given lambda on Linux x86_64. However, the c++filt tool is unable to unmangle it. It just outputs the input given to it, Z4mainEUlvE_.

如何解开它?

推荐答案

您可以使用GCC的 abi :: __ cxa_demangle 函数:

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

#include <memory>
#include <cstdlib>
#include <cxxabi.h>
#include <iostream>

// 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<char, malloc_deleter>;

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

输出

main::{lambda()#1}


b $ b

根据文档此函数返回使用零终止字符串> std :: malloc ,调用程序需要释放 std: :免费。此示例使用一个智能指针在范围结束时自动释放返回的字符串。

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.

这篇关于如何解开C ++ lambdas的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆