Created
July 29, 2016 06:53
-
-
Save xaxxon/2845c7376b21e5699872a00292f48340 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StackTraceException : public std::exception { | |
protected: | |
static constexpr int STACK_POINTER_COUNT = 100; | |
void * stack_pointers[STACK_POINTER_COUNT]; | |
std::size_t stack_pointers_filled = 0; | |
mutable std::string stacktrace; | |
public: | |
StackTraceException(); | |
~StackTraceException(); | |
virtual const char *what() const noexcept override; | |
}; | |
constexpr int StackTraceException::STACK_POINTER_COUNT; | |
StackTraceException::StackTraceException() { | |
stack_pointers_filled = backtrace(stack_pointers, STACK_POINTER_COUNT); | |
} | |
StackTraceException::~StackTraceException() { } | |
const char* StackTraceException::what() const noexcept { | |
// this is quite expensive, so only do it on demand | |
if (stacktrace == "") { | |
char **symbols = nullptr; | |
symbols = backtrace_symbols(stack_pointers, stack_pointers_filled); | |
std::stringstream stream; | |
for (int i = 0; i < stack_pointers_filled; i++) { | |
stream << symbols[i] << std::endl; | |
} | |
stacktrace = stream.str(); | |
free(symbols); | |
} | |
return stacktrace.c_str(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment