Re: Exception class with shift operator
On Jan 8, 11:41 pm, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
[...] Moreover, as noticed by Ulrich Eckhardt, the method what() is buggy
because it returns a pointer to a temporary string.
Yes, You are definitely right.
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
This implementation looks much better than mine, it works and - I
agree - it is much better
for what regards memory usage.
Following one comment by Ulrich Eckhardt about moving around a useless
stringstream,
I was thinking also to another possible implementation that avoids
completely the stringstream
as a member even as shared_ptr, based on creation of an instance of
stringstream only inside
operator<<:
template <typename T>
runtime_error& operator<<(const T& v)
{
std::stringstream ss(m_str);
ss << v;
m_str = ss.str();
return *this;
}
But, as far as I can see, this solution would imply much more overhead
both in operator<<
and in copy constructor. In summary, your solution seems to me more
efficient and robust,
while avoiding all the cons of maintaining a stringstream inside the
class.
Thanks a lot for your suggestions,
eca
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]