Effective C++ 笔记 —— Item 53: Pay attention to compiler warnings.

Many programmers routinely ignore compiler warnings. After all, if the problem were serious, it would be an error, right? This thinking may be relatively harmless in other languages, but in C++, it's a good bet compiler writers have a better grasp of what's going on than you do. For example, here's an error everybody makes at one time or another:

class B 
{
public:
    virtual void f() const;
};

class D : public B 
{
public:
    virtual void f();
};

The idea is for D::f to redefine the virtual function B::f, but there's a mistake: in B, f is a const member function, but in D it's not declared const. One compiler I know says this about that:

warning: D::f() hides virtual B::f()

Too many inexperienced programmers respond to this message by saying to themselves, "Of course D::f hides B::f — that’s what it’s supposed to do!" Wrong. This compiler is trying to tell you that the f declared in B has not been redeclared in D; instead, it's been hidden entirely (see Item 33 for a description of why this is so).

Things to Remember

  • Take compiler warnings seriously, and strive to compile warning free at the maximum warning level supported by your compilers.
  • Don't become dependent on compiler warnings, because different compilers warn about different things. Porting to a new compiler may eliminate warning messages you've come to rely on.

 

posted @ 2022-03-15 19:58  MyCPlusPlus  阅读(35)  评论(0编辑  收藏  举报