我尝试使用 abi::__cxa_demangle
来分解用户定义类型:
#include <iostream>
#include <mutex>
#include <memory>
#include <string>
#include <typeinfo>
#include <cassert>
#include <cstdlib>
#include <cxxabi.h>
namespace
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wexit-time-destructors"
std::mutex m;
std::unique_ptr< char, decltype(std::free) & > demangled_name{nullptr, std::free};
#pragma clang diagnostic pop
}
inline
std::string
get_demangled_name(char const * const symbol) noexcept
{
if (!symbol) {
return "<null>";
}
std::lock_guard< std::mutex > lock(m);
int status = -4;
demangled_name.reset(abi::__cxa_demangle(symbol, demangled_name.release(), nullptr, &status));
return ((status == 0) ? demangled_name.get() : symbol);
}
template< typename ...types >
void
f(std::size_t const i)
{
using F = void (*)();
assert(i < sizeof...(types));
static F const a[sizeof...(types)] = {static_cast< F >([] () { std::cout << get_demangled_name(typeid(types).name()) << std::endl; })...};
return a[i]();
};
struct A {};
struct B {};
struct X {};
struct Y {};
struct Z {};
int
main()
{
for (std::size_t i = 0; i < 5; ++i) {
f< A, B, X, Y, Z >(i);
}
return EXIT_SUCCESS;
}
但是abi::__cxa_demangle
返回status
"-3: One of the arguments is invalid."每两次。
第一次调用时(对于A
)智能指针包含nullptr
并且abi::__cxa_demangle
返回零status
"0: The demangling operation succeeded." 。但文档说:
output_buffer: A region of memory, allocated with malloc, of *length bytes, into which the demangled name is stored. If output_buffer is not long enough, it is expanded using realloc. output_buffer may instead be NULL; in that case, the demangled name is placed in a region of memory allocated with malloc.
因此,我得出结论,该函数无法重复使用其自身一致分配的内存。这是错误还是只是我对文档的误解?
最佳答案
您误解了文档:
output_buffer: A region of memory, allocated with malloc, of *length bytes
您正在传递使用 malloc
分配的内存区域,但 length
为 null,因此未定义 *length
。
为了知道是否可以重用内存,需要知道 block 有多大,因此需要传入长度作为第三个参数。
GCC 中的实现(实际上是在 libiberty support library 中):
if (output_buffer != NULL && length == NULL)
{
if (status != NULL)
*status = -3;
return NULL;
}
因此,如果您传递非空 output_buffer
指针,则还必须传递非空 length
指针。
由于您不知道分配的 block 有多大,因此您可以使用当前代码做的最好的事情是使用 strlen(demangled_name.get())+1
来查找最小长度肯定已经分配了。
更好的办法是保留一个存储先前大小的 size_t
全局变量,并将其传递进去。您可能应该将其全部包装在一个类中,而不仅仅是一堆全局变量。
关于c++ - abi::__cxa_demangle 无法重用其自身返回的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884628/