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" 
#include "boost/bind.hpp" 
#if GCC_IS_AT_LEAST(4, 6, 0)
  #pragma GCC diagnostic pop

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" 
.. code here ..
#ifdef __clang__
  #pragma clang diagnostic pop

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) :
    processHistoryPtr_(std::shared_ptr<ProcessHistory>(new ProcessHistory)),
    if (hist.isValid()) {
      assert(! ProcessHistoryRegistry::empty());
      bool found __attribute__((unused)) = ProcessHistoryRegistry::get(hist, *processHistoryPtr_);