用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_
。
我该如何解开它?
最佳答案
您可以使用 GCC 的特殊 abi::__cxa_demangle
函数:
#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}
根据The Documentation此函数返回使用 std::malloc 分配的 c 风格 零终止 字符串调用者需要使用 std::free 释放.此示例使用 智能指针 在作用域末尾自动释放返回的字符串。
关于c++ - 如何解开 C++ lambda 的错位名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534458/