【问题标题】:C++ did not generate warningC++ 没有产生警告
【发布时间】:2021-11-25 19:42:58
【问题描述】:

我的代码中有一个简单的错字。我想做const std::string a = b + "bar";,但意外得到const std::string a = a + "bar"; 令我惊讶的是,即使我使用-std=c++17 -Wall 编译,这也没有从GCC 9.3.0 产生任何警告。此外,我没有收到未使用变量b 的警告。这个怎么可能?我应该将哪些标志传递给 GCC 以生成至少一些警告来发现这个问题?

#include <string>
#include <iomanip>
#include <iostream>

namespace {
  const std::string b = "foo";
  const std::string a = a + "bar";
}

int main()
{
  std::cout << "a is " << std::quoted(a) << std::endl;
  return 0;
}

【问题讨论】:

  • 编译器不需要发出所有可能的警告,你可能偶然发现了 gcc 没有检测到的情况。 Clang 检测到 a-Wuninitialized 的无效使用。如果您认为 gcc 应该检测到这一点,请提交错误。

标签: c++ gcc gcc-warning


【解决方案1】:

您使用变量a 的方式,它有一个不确定值,它可以是陷阱表示未指定的值 .在某些情况下(实施)可能会导致未定义的行为

GCC 11.1.0 确实会生成警告,看起来像 here

#include <string>
#include <iomanip>
#include <iostream>



int main()
{
  int a = a + 1;//this generates warning in gcc 11.1.0
    std::string p = p + "some string";//this also generate warning in gcc 11.1.0
  return 0;
}

但 GCC 9.3.0 仅对 int 发出警告,如 here 所示

另一方面,clang gives 警告两者。

【讨论】:

  • 我同意这是一种未定义的行为。这显然是我的代码中的一个错误。问题是如何让 GCC 在编译时告诉我?
  • @PaulGrinberg 我不认为你可以;叮当声发现了它,但我无法让 GCC 报告它 - 直播 - godbolt.org/z/hqofx3fW1
猜你喜欢
  • 2022-08-04
  • 2017-02-18
  • 1970-01-01
  • 2015-02-06
  • 2018-12-25
  • 2015-07-22
  • 2012-03-19
  • 2023-03-03
  • 2011-06-02
相关资源
最近更新 更多