Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this noncompliant code example, the objects stored in the stdthe std::set have an overloaded operator< overloaded operator< implementation, allowing the objects to be compared with stdwith std::less. However, the comparison operation does not provide a strict weak ordering. Specifically, two sets, x and y, whose i values are both 1, but have differing j values can result in a situation where compwhere comp(x, y) and comp(y, x) are both false, failing the asymmetry requirements.

...

Compliant Solution

This compliant solution uses stduses std::tie() to properly implement the strict weak ordering operator< ordering operator< predicate.

Code Block
bgColor#ccccff
langcpp
#include <iostream>
#include <set>
#include <tuple>
 
class S {
  int i, j;
 
public:
  S(int i, int j) : i(i), j(j) {}
  
  friend bool operator<(const S &lhs, const S &rhs) {
    return std::tie(lhs.i, lhs.j) < std::tie(rhs.i, rhs.j);
  }
  
  friend std::ostream &operator<<(std::ostream &os, const S& o) {
    os << "i: " << o.i << ", j: " << o.j;
    return os;
  }
};

void f() {
  std::set<S> t{S(1, 1), S(1, 2), S(2, 1)};  
  for (auto v : t) {
    std::cout << v << std::endl;
  }
}

...

Using an invalid ordering rule can lead to erratic behavior or infinite loops.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CTR57-CPP

Low

Probable

High

P2

L3

Automated Detection

Tool

Version

Checker

Description

   

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C++3293
Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_CPP-CTR57-a

For associative containers never use comparison function returning true for equal values

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: CTR57-CPPChecks for predicate lacking strict weak ordering (rule partially covered).
 

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Bibliography

[ISO/IEC 14882-2014]

Subclause 23.2.4, "Associative Containers"

[Meyers
01
2001]Item 21, "Always Have Comparison Functions Return False for Equal Values"
[Sutter
04
2004]Item 83, "Use a Checked STL Implementation"

...


...

Image Modified Image Modified Image Modified