Site icon ivucica blog

Great new GCC option – Effective-C++ Warnings

Did you know about -Weffc++ in GCC? Neither did I, until I upgraded to new Code::Blocks from Jens’ unofficial Debian repository for Code::Blocks.

Here’s a few sample warnings, with sample lines and commentary:

Sample:
Position &operator=(const Position& other) { x=other.x; y=other.y; z=other.z; return *this;}

What’s the big deal here? By leaving out the ampersand in this operator overloading, I accidentally returned a copy of entire Position class. (On the other hand, I had no reason to actually overload this operator so perhaps real fix is to erase entire line. Still…)

No sample needed.

What’s the problem here? Well, we have a Mat class containing pointer. So what happens when someone does this: Mat x = y; or this: Mat x(y);? We have another instance of a class with copies of all the data, except the data pointed to by the pointer. Instead the pointer itself gets copied.

So if we keep a C-style string in there, we’re not really copying the string … we’re copying the pointer to it, and modifying the string in the new instance still modifies the string in the original ocpy.

While not applicable everywhere, still a good and useful warning.

Simple. Instead of initializing (or forgetting to initialize, or intentionally doing so) a variable in the constructor:
Obj() {m_classname=”Obj”; m_usecount = 0; }
why not do it in a “safe” and readable way (and perhaps more optimal?)
Obj() : m_classname(“Obj”), m_usecount(0) { }

While these warnings are certainly not the Universal Elixir to cure all your troubles, they will certainly prove useful in furthering your 1337 skills.


via blog.vucica.net