Re: Exception class with shift operator
Alberto Ganesh Barbati ha scritto:
eca ha scritto:
Can you see problems related to this class and its usage for the
purpose mentioned above?
It won't work because any exception class needs to be copy constructible
(???15.1/5), but yours class isn't copy constructible because of the
std::stringstream member.
Ops. That's what happen when you post too late at night. Sorry for
noise, of course your class is copy constructible, as you declared a
copy constructor. However, I am still greatly worried by your copy
constructor because you need to create a new stringstring and initialize
it with the text from the source stream. These operations aren't going
to be cheap and are going to need to allocate memory. As the exception
object is going to be copied during stack unwinding, you should mess
with memory the least possible. This problem can be eased by using a
shared_ptr.
Moreover, as noticed by Ulrich Eckhardt, the method what() is buggy
because it returns a pointer to a temporary string. I would therefore
rewrite the class like this:
namespace ext
{
class runtime_error : public std::exception
{
public:
runtime_error()
: my_ss(new ostringstream)
{}
explicit runtime_error(const std::string& arg)
: my_ss(new ostringstream(arg))
{}
runtime_error(const runtime_error& e)
: my_ss(e.my_ss)
{}
runtime_error& operator=(const runtime_error& e)
{
my_ss = e.my_ss;
return *this;
}
virtual ~runtime_error() throw()
{}
public:
virtual const char* what() const throw()
{
if (m_str.empty())
m_str = my_ss->str();
return m_str.c_str();
}
template <typename T>
runtime_error& operator<<(const T& v)
{
*my_ss << v;
m_str.clear();
return *this;
}
private:
std::tr1::shared_ptr<std::ostringstream> my_ss;
mutable std::string m_str;
};
}
Frankly, I don't like this approach very much, but at least it should work.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]