问题
What is the reason for the g++ abi::__cxa_demangle
function to not return the return value for member functions?
Here's a working example of this behavior
#include <execinfo.h>
#include <cxxabi.h>
#include <iostream>
struct Foo {
void operator()() const
{
constexpr int buf_size = 100;
static void *buffer[buf_size];
int nptrs = backtrace(buffer, buf_size);
char **strings = backtrace_symbols(buffer, nptrs);
for(int i = 0; i < nptrs; ++i) {
auto str = std::string(strings[i]);
auto first = str.find_last_of('(') + 1;
auto last = str.find_last_of(')');
auto mas = str.find_last_of('+');
int status;
char* result = abi::__cxa_demangle(str.substr(first, mas-first).c_str(), nullptr, nullptr, &status);
if (status == 0) std::cout << result << std::endl;
}
}
};
int main () {
Foo f;
f();
}
and after compiling with
g++ foo.cpp -std=c++11 -rdynamic
the output is
Foo::operator()() const
Is there a way to get a consistent behavior, this is, getting also the return value for the member functions?
回答1:
Mangling/demangling of function names is beyond the scope of the C++ Standard. It's purely compiler's responsibility and necessity to mangle functions in such way that two different functions will have different mangled representations (symbols).
In the same time, as declaring two functions that only differ by their return type is prohibited by the Standard, there's no need for the compiler to mangle the return type, as there will be no benefit.
What you are seeing is just a consequence of the compiler being reasonably lazy.
Also, here's a rextester with a more complete example (including a global function in the backtrace).
来源:https://stackoverflow.com/questions/44914938/return-type-in-demangled-member-function-name