I have the following program:
#include <string>
#include <iostream>
#include <stdexcept>
#include <sstream>
enum class Severity
{
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL,
};
struct LogRecord
{
const Severity mSeverity;
const std::string mTimestamp;
const char* const mFunc;
const size_t mLine;
const char* const mFile;
std::string mMessage;
std::exception mException;
LogRecord& operator<<(const std::exception& e)
{
mException = e;
return *this;
}
template <typename T>
LogRecord& operator<<(const T& msg)
{
std::ostringstream ss;
ss << msg;
mMessage += ss.str();
return *this;
}
};
void throw_exception()
{
throw std::logic_error("Logic error");
}
int main()
{
LogRecord l{};
try
{
throw_exception();
}
catch(std::exception& e)
{
l << "Test" << e;
std::cout << l.mMessage << ": " << l.mException.what() << std::endl;
}
}
The main function prints "Test: std::exception" instead of "Test: Logic error". The reason is that "mException = e;" does not copy the exception to the mException member of my struct. What is the reason for that and how could I archieve that "Test: Logic error" is printed?