Next: High Integrity CPP Guideline 17.18  Up: 17 Standard Template Library (STL)  Previous: High Integrity CPP Guideline 17.16  Contents

High Integrity CPP Rule 17.17   The result of a predicate should depend only on its parameters.

Justification

For certain algorithms there is no requirement that the order of evaluation, or even that the same predicate object be used, when iterating through a container. A predicate should not be dependent on the order of evaluation; it should return the same result for an element regardless of previous calls or any external state.

In addition, algorithms can copy predicates so there is no guarantee that the state of the predicate will be maintained.

By declaring operator() const it is explicit that the state of the predicate is not modified by calling the function.

   
   class Bad_Predicate
   {
   public:
      Bad_Predicate() : m_count( 0 ) {}
      bool operator()( const int& )
      {
         return ++m_count == 5; 
      }
   private:
      int m_count;
   };
   
   // Irrespective of the number of elements in the deque m_count
   // may never reach 5 as the predicate might be copied.
   //
   bool is_large_deque( std::deque< int >& d )
   {
      return d.end() != 
             std::find_if( d.begin(), d.end(), Bad_Predicate() );
   } 
Reference

Effective STL Item 39;


HICPP VERSION 2.4  http://www.codingstandard.com   Copyright: © 2007 THE PROGRAMMING RESEARCH GROUP