Skip to content

Commit 91e4255

Browse files
Avoid rand() in the legacy tr1 test suite (#4921)
1 parent 1acbeae commit 91e4255

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

tests/tr1/tests/algorithm/test.cpp

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <algorithm>
1212
#include <ctype.h>
1313
#include <functional>
14+
#include <random>
1415
#include <string.h>
1516

1617
// FUNCTION OBJECTS
@@ -294,15 +295,13 @@ void test_copy(char* first, char* last, char* dest) { // test copying template f
294295
CHECK_STR(array2, "aaxx");
295296
}
296297

297-
CSTD size_t frand(CSTD size_t nmax) { // return random value in [0, nmax)
298-
return CSTD rand() % nmax;
299-
}
300-
301298
struct rand_gen { // uniform random number generator
299+
STD mt19937 mt;
300+
302301
typedef CSTD size_t result_type;
303302

304303
result_type operator()() { // get random value
305-
return CSTD rand() & 0xfffff;
304+
return mt() & 0xfffff;
306305
}
307306

308307
static result_type(min)() { // get minimum value
@@ -429,8 +428,13 @@ void test_mutate(char* first, char* last, char* dest) { // test mutating templat
429428
CHECK_STR(array, "ebgf");
430429

431430
STD random_shuffle(first, last);
432-
CSTD size_t (*prand)(CSTD size_t) = &frand;
433-
STD random_shuffle(first, last, prand);
431+
432+
STD mt19937 mt;
433+
auto rng_func = [&mt](CSTD size_t nmax) { // return random value in [0, nmax)
434+
STD uniform_int_distribution<CSTD size_t> dist{0, nmax - 1};
435+
return dist(mt);
436+
};
437+
STD random_shuffle(first, last, rng_func);
434438

435439
rand_gen urng;
436440
STD shuffle(first, last, urng);

tests/tr1/tests/memory2/test.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@
77
#include "tdefs.h"
88
#include <memory>
99
#include <mutex>
10-
#include <stdlib.h>
10+
#include <random>
1111
#include <thread>
1212
#include <vector>
1313

1414
using STD shared_ptr;
1515
using STD weak_ptr;
1616

1717
using STD lock_guard;
18+
using STD mt19937;
1819
using STD mutex;
1920
using STD thread;
2021
using STD vector;
@@ -27,14 +28,15 @@ static shared_ptr<int> sp;
2728
static mutex start_mtx;
2829

2930
static void ctors() { // construct a gazillion shared and weak pointers
31+
mt19937 mt;
3032

3133
{ // wait for access
3234
lock_guard<mutex> lock(start_mtx);
3335
}
3436

3537
for (int i = 0; i < NSETS; ++i) {
3638
for (int j = 0; j < NREPS; ++j) {
37-
if (rand() % 2 != 0) {
39+
if (mt() % 2 != 0) {
3840
shared_ptr<int> sp0(sp);
3941
} else {
4042
weak_ptr<int> wp0(sp);

0 commit comments

Comments
 (0)