Project

General

Profile

Various helpful tips for coding in the CET C++ environment

1. Dealing with warnings

Warnings are often an indication of problems in the code. We suggest compiling with -Werror whenever possible. This is standard for all CET packages. -Werror treats all warnings as errors. This stops compilation, allowing you to fix the code.

1.1 Using pragma push and pop

Unfortunately, a compiler will occasionally issue a warning about code which is both permissible and desired. To avoid trapping these warnings, we use the #pragma push/pop feature (available since gcc 4.6).

This example is from cpp0x.

#if GCC_IS_AT_LEAST(4, 6, 0)
  #pragma GCC diagnostic push
  #pragma GCC diagnostic ignored "-Wstrict-aliasing" 
#endif
#include "boost/bind.hpp" 
#if GCC_IS_AT_LEAST(4, 6, 0)
  #pragma GCC diagnostic pop
#endif

The clang compiler has the same functionality. This example is from CLHEP Utility.

#ifdef __clang__
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor" 
#endif
.. code here ..
#ifdef __clang__
  #pragma clang diagnostic pop
#endif

1.2 Warnings about unused variables

If the variable is really unused, it should not be defined.

However, if blocks that are only exercised for certain conditions sometimes cause spurious warnings. In that case declaring an unused attribute can be helpful.

Consider this bit of code from art.

  Principal::Principal(ProcessConfiguration const& pc,
                       ProcessHistoryID const& hist,
                       std::unique_ptr<BranchMapper> && mapper,
                       std::unique_ptr<DelayedReader> && rtrv) :
    boost::noncopyable(),
    processHistoryPtr_(std::shared_ptr<ProcessHistory>(new ProcessHistory)),
    processConfiguration_(pc),
    processHistoryModified_(false),
    groups_(),
    branchMapperPtr_(mapper.release()),
    store_(rtrv.release())
  {
    if (hist.isValid()) {
      assert(! ProcessHistoryRegistry::empty());
      bool found __attribute__((unused)) = ProcessHistoryRegistry::get(hist, *processHistoryPtr_);
      assert(found);
    }
  }