本篇介绍几个细琐的小特性,可以使代码更加安全可靠。 最常见的情况是采取 for loop 遍历某个容器,比如: std::vector<int> v(10); std::ranges::iota(v, 0); for (int i = v.size() – 1; i >= 0; –i) { std::cout << v[i] << ' '; } 乍看之下,似乎并无问题,但实际上却存在安全隐患,若是 v.size() 的结果大于 std::numeric_limits<int>::max(),将产生 UB。 倘若你使用了类型推导,问题会更加明显。 for (auto i = v.size() – 1; i >= 0; –i) { std::cout << v[i] <<… Continue Reading 使用 C++20 安全地比较不同类型的整型值

What are the ranking rules for reference bindings? Let’s consider the following example: void f(int);         // #1 void f(int&);        // #2 void f(int const&);  // #3 void f(int&&);       // #4 void f(int const&&); // #5 Here are some key points: #1 is a function that accepts borrowed int arguments. #2 is a function that takes an lvalue reference. #3 is a function that takes… Continue Reading Normal OR Rules for Reference Bindings

本篇分享详细解释一下 Top-level const 和 Low-level const 的概念。 Top-level 和 Low-level 指的是名称修饰符所处的位置,const 是最常见的修饰符,举一反三,便可知所有情况。 由例子切入理解: int a = 42; int b = 10; int* const p1 = &a; // top-level const *p1 = 22; // Ok p1 = &b; // Error! int const* p2 = &a; // low-level const *p2 = 22;… Continue Reading T240516 Top-level const and Low-level const