Today in university I was recommended by a professor that I'd check for (this != ©)
in the copy constructor, similarly to how you should do it when overloading operator=
. However I questioned that because I can't think of any situation where this
would ever be equal to the argument when constructing an object.
He admitted that I made a good point. So, my question is, does it make sense to perform this checking, or is it impossible that this would screw up?
Edit: I guess I was right, but I'll just leave this open for a while. Maybe someone's coming up with some crazy cryptic c++ magic.
Edit2: Test a(a)
compiles on MinGW, but not MSVS10. Test a = a
compiles on both, so I assume gcc will behave somewhat similar. Unfortunately, VS does not show a debug message with "Variable a used without being initialized". It does however properly show this message for int i = i
. Could this actually be considered a c++ language flaw?
class Test
{
Test(const Test ©)
{
if (this != ©) // <-- this line: yay or nay?
{
}
}
Test &operator=(const Test &rhd)
{
if (this != &rhd) // <-- in this case, it makes sense
{
}
}
};
a
) without calling any constructor for it (not even default constructor). When you then copy an unconstructed object, all your RAII endeavors will be screwed up. To make it worse, without further checking, the code won't even crash until destruction of the original©
object. Sure, these assignments are nothing but wrong, but IMO they should also be considered wrong then, by K&R C already. Even copy and swap could screw up device handles etc. – TangramTest a; a.~Test();
. So what? – Birkle