【问题标题】:constexpr constructor won't show coverage dataconstexpr 构造函数不会显示覆盖数据
【发布时间】:2018-05-28 22:27:59
【问题描述】:

今天我将我的矩阵类重写为constexpr。我对这个类有 100% 的单元测试覆盖率,但我注意到在将几乎所有函数转换为 constexpr 后,构造函数的一部分在 lcov 中被标记为根本不再覆盖。

这是只有构造函数的类。

template<typename T, std::size_t m, std::size_t n>
class Matrix
{
static_assert(std::is_arithmetic<T>::value,
                  "Matrix can only be declared with a type where "
                  "std::is_arithmetic is true.");

public:
    constexpr Matrix(
        std::initializer_list<std::initializer_list<T>> matrix_data)
    {
        if (matrix_data.size() != m)
        {
            throw std::invalid_argument("Invalid amount of rows.");
        }

        for (const auto& col : matrix_data)
        {
            if (col.size() != n)
            {
                throw std::invalid_argument("Invalid amount of columns.");
            }
        }


        std::size_t pos_i = 0;
        std::size_t pos_j = 0;

        for (auto i = matrix_data.begin(); i != matrix_data.end(); ++i)
        {
            for (auto j = i->begin(); j != i->end(); ++j)
            {
                this->data[pos_i][pos_j] = *j;
                ++pos_j;
            }
            ++pos_i;
            pos_j = 0;
        }
    }


private:
    std::array<std::array<T, n>, m> data{};

};


int main()
{
    Matrix<double, 2, 2> mat = {
        {1, 2},
        {3, 4}
    };

    return 0;
}

我正在使用 gcc 7.2 和 lcov 1.13

【问题讨论】:

  • 这里问了什么?
  • @ÖöTiib 为什么constexpr 代码在启用gcov 时不会产生任何覆盖率数据。

标签: c++ unit-testing code-coverage gcov lcov


【解决方案1】:

我对这个类有 100% 的单元测试覆盖率,但我注意到在将几乎所有函数转换为 constexpr 后,构造函数的一部分在 lcov 中被标记为根本不再覆盖。

lcov未覆盖代码的指示意味着gcov 没有对其进行检测。

标记为constexpr 的任何内容都在编译时 进行评估,gcov 覆盖率数据在运行时 收集>.

所以这是我怀疑的一个原因,为什么你没有得到任何 constexpr 函数的覆盖率数据。


由于您有模板化代码,我不确定我是否是最新的,但我体验到gcov 不能很好地检测模板,您可能会得到它们的零覆盖率数据。

与我上面对constexpr 所说的类似推理,模板是在编译时评估/实例化的。至少很难以合理的方式检测所有实际使用的模板实例化。

【讨论】:

  • "被评估" -> "可能被评估,除非它被用来定义一个值模板参数,在这种情况下它在编译时被评估"。
  • @rubenvb 好吧,据我所知,gcov 根本不能很好地处理模板代码。也许这是主要原因。
猜你喜欢
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 2011-07-20
  • 2015-02-01
  • 1970-01-01
相关资源
最近更新 更多