Rule A26-5-2 (required, implementation, automated)

Random number engines shall not be default-initialized.

Rationale

Using a pseudo-random number generator gives different results that depend on a used seed value. Initializing random number engines by default initializes pseudorandom generator with a default_seed constant value. However, this can be not obvious for a developer and can lead to unexpected program behaviour (generating the same random sequences among different program executions).

Exception

For consistent testing purposes it can be convenient to seed the random number engine with a fixed value to get a deterministic sequence, but never within production code where real randomness is required, e.g. for security reasons.

Example

// $Id: A26-5-2.cpp 311495 2018-03-13 13:02:54Z michal.szczepankiewicz $

#include <iostream>
#include <random>

int main()
{
std::random_device rd;
std::default_random_engine eng{rd()}; //compliant
std::uniform_int_distribution<int> ud{0, 100};
int r1 = ud(eng);
std::cout << "Random value using std::random_device: " << r1 << std::endl;

std::default_random_engine eng2{}; //non-compliant
std::uniform_int_distribution<int> ud2{0, 100};
int r2 = ud2(eng);
std::cout << "Random value using std::random_device: " << r2 << std::endl;

return 0;
}

See also

SEI CERT C++ Coding Standard [10]: MSC51-CPP: Ensure your random number generator is properly seeded.