代码之家  ›  专栏  ›  技术社区  ›  Aykhan Hagverdili

如何使用std-span进行边界检查?

  •  1
  • Aykhan Hagverdili  · 技术社区  · 6 年前

    std::vector 几乎所有其他容器都有一种非常方便的边界检查方法: at() . std::span 显然没有。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Alberto    6 年前

    很笨重,但像这样:

    1. 使用位置
    template<class Container>
    auto& at(Container&& c, std::size_t pos){
        if(pos >= c.size())
            throw std::out_of_range("out of bounds");
        return c[pos];
    }
    
    1. 使用迭代器:
    template<class Iterator, class Container>
    auto& at(Container&& c, Iterator&& it){
        if(std::distance(c.begin(), it) >= c.size())
            throw std::out_of_range("out of bounds");
        return *it;
    }
    
        2
  •  0
  •   ecatmur    6 年前

    这个 paper

    距离检查与边界安全

    在跨度范围内。在运行时,由于未能满足spans boundssafety约束,实际发生的是未定义的行为。

    如果您的标准库不允许您将行为控制到适当的粒度。 gsl-lite 提供具有可配置的违反合同行为的插入式替换。这个 Microsoft GSL 以前是可配置的,但是 now 总是因为违反合同而终止合同,讨论 here

    推荐文章