c++ - 成员模板出现奇怪的 PC-Lint 错误

标签 c++ templates pc-lint

我目前正在努力使用 PC-Lint(版本 9.00j 和 l),它为我的一段代码提供了一些错误和警告。代码编译良好并按预期运行。这是它的简化版本:

#include <iostream>
#include <vector>

typedef unsigned char uint8_t;

class Test
{
  uint8_t          inputList[10];
  std::vector<int> resultList;

public:

  Test() : resultList()
  {
    for (uint8_t ii = 0; ii < 10; ++ii) 
      inputList[ii] = ii;
  }

  template<int list_size, typename ResultListType>
  void loadList(const uint8_t (& inputList)[list_size],
                ResultListType & resultList) const
  {
    for (uint8_t ii = 0; ii < list_size; ++ii) 
      resultList.push_back(inputList[ii]);
  }

  void run()
  {
    loadList(inputList, resultList);
  }

  void print()
  {
    std::vector<int>::iterator it;
    for (it = resultList.begin(); it != resultList.end(); ++it)
      std::cout << *it << std::endl;
  }
};

int main()
{
  Test t;
  t.run();
  t.print();
}

在 Gimpel 的在线演示中运行它时,我收到以下错误和警告:

    30      loadList(inputList, resultList);
diy.cpp  30  Error 1025:  No template matches invocation 'Test::loadList(unsigned char [10], std::vector<int>)', 1 candidates found, 1 matched the argument count
diy.cpp  30  Info 1703:  Function 'Test::loadList(const unsigned char (&)[V], <2>&) const' arbitrarily selected. Refer to Error 1025
diy.cpp  30  Error 1032:  Member 'loadList' cannot be called without object
diy.cpp  30  Error 1058:  While calling 'Test::loadList(const unsigned char (&)[V], <2>&) const': Initializing a non-const reference '<2>&' with a non-lvalue (a temporary object of type 'std::vector<int>')
diy.cpp  30  Warning 1514:  Creating temporary to copy 'std::vector<int>' to '<2>&' (context: arg. no. 2)

所以基本上,PC-Lint 试图告诉我它会偶然找到正确的模板参数,并且只会填充 vector 的临时拷贝。但是代码运行良好,结果列表包含数据!

谁能告诉我这是怎么回事? PC-Lint 是正确的还是出问题了,或者这只是一个 PC-Lint 错误?

最佳答案

问题是 loadList 被标记为 const,然而你传递了一个非常量引用给成员变量 resultList修改

的确,loadList 函数不会直接修改this 实例,但由于您仍然修改成员变量,因此该函数不能保持不变。

要么创建一个传递给函数的临时 vector ,要么使函数不是const

关于c++ - 成员模板出现奇怪的 PC-Lint 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307170/

相关文章:

带有 user.is_authenticated 的 Django 模板标签 + 模板不起作用

c++ - 有没有人有使用 pc-lint 的好技巧?

c++ - 在不同的 .cpp 文件中使用结构

c++ - 为什么 BGL 函数的参数用点而不是逗号分隔?

c++ - 在 TensorFlow 上创建优化器的步骤

regex - 按缩进模式处理文本文件

c - 如何跳过 C 文件的所有 lint 错误

C++关于返回值优化的问题

c++ - 从模板中提取与参数无关的代码

c++ - 模板 --> 如何破译、必要时决定和创建?