败犬日报 2025-06-19
1. cppreference 有没有 dark mode
可以尝试 https://github.com/std-microblock/cpp-reference-refined
2. code is cheap, show me the talk
3. std::replace 传元素引用的坑
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string s = "a1b2a3";
std::replace(s.begin(), s.end(), s[0], '9');
std::cout << s << "\n";
}
可能的结果是 "91b2a3" (GCC 15.1 无编译参数),只替换了 s[0]
。因为 std::replace
的第三个参数是 const T&
,这个值在函数里发生了改变。
推荐方法:
std::replace(s.begin(), s.end(), auto{s[0]}, '9');
// 更新:移除了 (char)s[0] / +s[0] / char target = s[0]; 做法,统一为 auto{s[0]}
这个是真的坑,很多 algorithm 函数都传引用。cppref 的 Notes 也提到了这点。https://en.cppreference.com/w/cpp/algorithm/replace.html
Because the algorithm takes old_value and new_value by reference, it can have unexpected behavior if either is a reference to an element of the range [first, last).
同款问题 https://www.zhihu.com/question/630025869。
4. std::apply
有什么用
这个函数把 tuple 展开为参数给函数调用。visitor 模式会用到。
5. C 里用 CPS 风格
https://godbolt.org/z/ePTqrs3no,群友给的 demo,没看懂。
6. 如何看待 Rust 写的 PNG 解码器比 C 实现更快? - 圆角骑士魔理沙的回答 - 知乎
https://www.zhihu.com/question/6568018545/answer/55004999007
这个回答有很多事实性错误,三目运算 (A ? B : C
) 会很容易编译到 cmov,自动向量化、手动向量化(intrinsic 函数)都是有的。
唯一 rust 明显有优势的就是 safe rust 的引用都默认 noalias,在 C 里要手动加 restrict。可以认为 safe rust 下限高,C 上限高。