Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor editorial changes

...

The C++ standard library provides mechanisms for fine-grained control over pseudorandom number generation. It breaks random number generation down into two parts: one part is the algorithm responsible for providing random values (the engine), and the other is responsible for distribution of the random values via a density function (the distribution). The distribution object is not strictly required, but it works to ensure that values are properly distributed within a given range instead of improperly distributed due to bias issues. This compliant solution uses the Mersenne Twister algorithm as the engine for generating random values and a uniform distribution to negate the modulo bias from the noncompliant code example:.

Code Block
bgColor#ccccff
langcpp
#include <random>
#include <string>
 
void f() {
  std::string id("ID"); // Holds the ID, starting with the characters "ID" followed
                        // by a random integer in the range [0-10000].
  std::uniform_int_distribution<int> distribution(0, 10000);
  std::random_device rd;
  std::mt19937 engine(rd());
  id += std::to_string(distribution(engine));
  // ...
}

Note that this This compliant solution also seeds the random number engine, in conformance with MSC51-CPP. Ensure your random number generator is properly seeded.

Risk Assessment

Using the std::rand() function could lead to predictable random numbers.

...