Is a Swappable class allowed to throw an exception?
Howard Hinnant wrote:
Thanks Niels. I think you make a good point. I've opened LWG issue 594.
Thank you, Howard! Hopefully providing an appropriate specialization of
std::swap will be sufficient to make a class Swappable in C++0x...
Yet another Swappable question, though. Is it allowed for a Swappable
class to throw an exception, while swapping?
For example, my BadCopier class (see below) throws a bad_alloc in its
copy constructor, as well as in its assignment operator, but still it is
both CopyConstructible and Assignable, or not? So is it Swappable?
My BadSwapper class (further below) throws a bad_alloc whenever its swap
function is called. Still... is it Swappable as well? I doubt it, as
it doesn't meet the post-condition for swap(t, u), as described in the
Draft, Table 32, Swappable requirements:
"t has the value originally held by u, and u has the value originally
held by t."
(Draft: www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf)
Here are my "bad" classes:
------------------------------------------------------------------------
class BadCopier
{
int m_data;
public:
explicit BadCopier(int arg = 0): m_data(arg) {}
BadCopier(const BadCopier& rhs): m_data(rhs.m_data)
{
throw std::bad_alloc();
}
BadCopier & operator=(const BadCopier& rhs)
{
m_data = rhs.m_data;
throw std::bad_alloc();
}
};
class BadSwapper
{
int m_data;
public:
explicit BadSwapper(int arg = 0): m_data(arg) {}
friend void swap(BadSwapper& lhs, BadSwapper& rhs)
{
std::swap(lhs.m_data, rhs.m_data);
throw std::bad_alloc();
}
};
------------------------------------------------------------------------
Please let me know if both classes satisfy the Swappable requirements!
Kind regards,
Niels Dekker
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]