c++ 最佳实践

工程

工具

网络

服务治理

配置中心

定义全局变量

1
2
3
4
5
6
7
8
9
// global.h
namespace {
extern int i;
}

// global.cpp
namespace {
int i = 1024;
}

随机数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// random_util.h
#include "random"
#include "climits"
namespace utils {
extern std::random_device gRandomDev;
extern std::mt19937 gRandomGenerator;
extern std::uniform_int_distribution<std::mt19937::result_type> gRandomDist; // (0, INT_MAX)

uint32_t RandomInt(const int &min = 0, const int &max = 0);
}

// random_util.cpp
#include "random_util.h"
namespace ranker::utils {
std::random_device gRandomDev;
std::mt19937 gRandomGenerator(gRandomDev());
std::uniform_int_distribution<std::mt19937::result_type> gRandomDist(0, INT_MAX);

uint32_t RandomInt(const int &min, const int &max) {
if (min == max && min == 0) {
return (uint32_t) gRandomDist(gRandomGenerator);
} else {
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
return (uint32_t) dist(gRandomGenerator);
}
}
}

/*
满足泊松分布的随机数
std::poisson_distribution<> d{/*mean=*/4};
d(gRandomGenerator);
*/