Skip to content

败犬日报 2025-04-16

1. std::get<0>(tuple) 太丑了

tuple 如果不用来结构化绑定,那就不要写 tuple 了。

struct 的字段自带名字,语义上更清晰。

2. 多继承的最佳实践

最佳实践应该是单继承 + 接口(在 C++ 中是不带成员变量的类)。其他形式的多继承甚至菱形继承都会带来复杂性,应尽可能避免。

3. 团队的不同人 format 配置不一样,一保存代码全是修改

项目里放一个 .clang-format 是最合理最简单的。

4. 线程安全随机数和 thread_local magic static

往期 介绍了 magic static,为了保证线程安全会加锁。如果用 thread_local 就不会加锁。

推荐线程安全随机数使用这个小寄巧。

cpp
// 这个代码偷懒用了 openmp 的多线程,编译参数要加 -fopenmp
#include <cstdio>
#include <random>

int randint(int min, int max) {
    static thread_local std::mt19937 generator(std::random_device{}());
    std::uniform_int_distribution<int> distribution(min, max);
    return distribution(generator);
}

int main() {
#pragma omp parallel
    printf("%d\n", randint(1, 10));
}

代码参考:https://stackoverflow.com/questions/21237905/how-do-i-generate-thread-safe-uniform-random-numbers