Thursday, November 27, 2008

Why following the standard is the right thing..

Today I saw an interesting example of bad C++ coding:

Let's say we have a class, named A, that have a strange copy constructor prototype:

class A {
public:
A(A& an_a) {...}
[...]
}

the standard says that the copy constructor for a type T has to have this prototype:

T(const T&);

so, the instance passed as argument has to be const!

My compiler (g++ 4.2.4), doesn't complain even if I specify -Wall and -pedantic, and the code is generated...

Let's go ahead, let's say we have a class MyClass that has an attribute of type A, and this method:

A MyClass::getA() const {return this->the_a;}

We don't return a reference to the attribute, we want to return a copy, no matter why...

We aren't using this method yet, but we are careful programmers so we try to compile our code... surprise! The compile complains because it's missing a A::A(A) constructor... damn, why it isn't using the copy constructor we wrote??? Oh yes!, the getA() method is const! Let's erase that swaerword!!! Oh, that's fine, the compilers doesn't complain anymore!

Now, we want to use our nice method so somewhere we have something like this:

A my_a = my_class.getA();

What? The compiler complains again? The same error? What does he wants? Nothing here is const!!!

And that's the truth: we didn't follow the standard and the standard punished ourselves! The compiler need to do a copy of a temporary variable and temporary variables in C++ are all const! If you try to add a constructor like this:

A::A(A)

the compilers will complain for a wrong constructor too! That's the end, we have to bow our heads and follow the standard

The moral of the story is: you have to follow the standard, otherwise the standard will have its revenge!

PS Is it possible to read code like that written by a senior C++ developer?????

No comments: