class Exception : public std::exception
{
public:
explicit Exception(const char* what);
explicit Exception(const string& what);
virtual ~Exception() throw();
virtual const char* what() const throw();
const char* stackTrace() const throw();
private:
void fillStackTrace();
string message_;
string stack_;
};
Exception::Exception(const char* msg)
: message_(msg)
{
fillStackTrace();
}
Exception::Exception(const string& msg)
: message_(msg)
{
fillStackTrace();
}
Exception::~Exception() throw ()
{
}
const char* Exception::what() const throw()
{
return message_.c_str();
}
const char* Exception::stackTrace() const throw()
{
return stack_.c_str();
}
void Exception::fillStackTrace()
{
const int len = 200;
void* buffer[len];
//該函數用於獲取當前線程的調用堆棧,獲取的信息將會被存放在buffer中,它是一個指針數組
int nptrs = ::backtrace(buffer, len);//猜測是得到trace的數量,每個trace存到buffer[i]裏,即從[0]到[nptrs-1]
char** strings = ::backtrace_symbols(buffer, nptrs);//直接返回這個buffer內的可打印信息
if (strings)
{
for (int i = 0; i < nptrs; ++i)
{
// TODO demangle funcion name with abi::__cxa_demangle
stack_.append(strings[i]);
stack_.push_back('\n');
}
free(strings);//直接free即可!也就是說malloc的是一個一維數組,只是邏輯成二維;
}
}