According to CERT, function rand
does not have “good statistical properties” and can be predictable, which makes programs that use rand
less secure (CERT guideline MSC30-CPP). As we mentioned in Section 6.6, C++11 provides a new, more secure library of random-number capabilities that can produce nondeterministic random numbers for simulations and security scenarios where predictability is undesirable. These new capabilities are located in the C++ Standard Library’s <random>
header.
Random-number generation is a mathematically sophisticated topic for which mathematicians have developed many random-number generation algorithms with different statistical properties. For flexibility based on how random numbers are used in programs, C++11 provides many classes that represent various random-number generation engines and distributions. An engine implements a random-number generation algorithm that produce pseudorandom numbers. A distribution controls the range of values produced by an engine, the types of those values (e.g., int
, double
, etc.) and the statistical properties of the values. In this section, we’ll use the default random-number generation engine—default_random_engine—and a uniform_int_distribution, which evenly distributes pseudorandom integers over a specified range of values. The default range is from 0 to the maximum value of an int
on your platform.