Skip to content

败犬日报 2025-02-17

1. constexpr if 的条件没有 SFINAE

要套个 requires 或者使用辅助的 SFINAE 函数。

2. 三目运算符的类型

https://zh.cppreference.com/w/cpp/language/operator_other 详细说明了六个阶段,简单来说是一个尝试兼容三目运算符两个分支的类型;如果两个类型无关,那编译直接不过。

3. 标记访问某个变量时必须持有某个锁

Clang 的 Thread Safety Analysis。

https://clang.llvm.org/docs/ThreadSafetyAnalysis.html

https://www.cnblogs.com/jicanghai/p/9472001.html

还能报告句柄竞争。

cpp
struct BankAccount {
    Mutex mu;
    int balance GUARDED_BY(mu);
};

4. 为什么 cpp 的 mutex 不像别的语言那样能包在变量上呢

因为最开始 mutex 语义就是独立的。

5. shared_ptr<void>

其实就是 void * 的共享指针,一些功能和 void * 类似。

6. unique_ptr 的错误用法

cpp
int *rawPtr = new int(42);
std::unique_ptr<int> ptr1(rawPtr);
std::unique_ptr<int> ptr2(rawPtr);

经典的 double free。

使用了裸指针就有义务去管理好它的所有权,硬要乱来神仙也救不了。这个问题也可以用 make_unique 来避免裸指针。