Skip to content
败犬日报 2025-11-24

败犬日报 2025-11-24

1. 为什么 int a[10]; int* p = a + 11; 是未定义行为,int* p = reinterpret_cast<int*>(114514); 不是未定义行为

偷点周刊群话题。

这是加法 UB 了。指针算术是有要求的,大致意思是数组里指针的加减不能移出数组范围 [begin, end](包括末尾元素的后一个)。(cppref 里的 Pointer arithmetic 章节)

而整数转换到指针是任何条件都不 UB 的。(cppref 里的 A value of any integral or enumeration type can be converted to a pointer type)


还有个令人费解的操作,就是 int* p = a + 11; 改成 int* p = reinterpret_cast<int*>(reinterpret_cast<size_t>(a) + 11 * sizeof(int)); 就不是未定义行为了,看似一样的行为实则不然。

(c++ 为什么这么设计,群友没说)

2. views::filter + views::tranform 会重复计算 filter pred

得手动加 cache_latest。