警告:此功能未初始化时使用了<< anonymous>'[-Wuninitialized]

时间:2019-05-03 20:04:43

标签: c++

以下程序使用-O0编译时没有警告:

#include <iostream>

struct Foo
{
  int const& x_;
  inline operator bool() const { return true; }
  Foo(int const& x):x_{x} { }
  Foo(Foo const&) = delete;
  Foo& operator=(Foo const&) = delete;
};

int main()
{
  if (Foo const& foo = Foo(3))
    std::cout << foo.x_ << std::endl;

  return 0;
}

但是如果-O1或更高,则会发出警告:

maybe-uninitialized.cpp: In function ‘int main()’:
maybe-uninitialized.cpp:15:22: warning: ‘<anonymous>’ is used uninitialized in this function [-Wuninitialized]
 std::cout << foo.x_ << std::endl;

您如何摆脱-O1及更高版本的警告?

这样做的动机是为了使用CHECK(x)宏,该宏必须捕获const引用而不是值,以免触发析构函数,复制构造函数等,并打印出一个值。

解决方案在底部

编辑:

$ g++ --version
g++ (GCC) 8.2.1 20181127

No warnings:  g++ maybe-uninitialized.cpp -Wall -O0
With warning: g++ maybe-uninitialized.cpp -Wall -O1

编辑2以响应@Brian

#include <iostream>

struct CheckEq
{
  int const& x_;
  int const& y_;
  bool const result_;
  inline operator bool() const { return !result_; }
  CheckEq(int const& x, int const &y):x_{x},y_{y},result_{x_ == y_} { }
  CheckEq(CheckEq const&) = delete;
  CheckEq& operator=(CheckEq const&) = delete;
};

#define CHECK_EQ(x, y) if (CheckEq const& check_eq = CheckEq(x,y)) \
  std::cout << #x << " != " << #y \
    << " (" << check_eq.x_ << " != " << check_eq.y_ << ") "

int main()
{
  CHECK_EQ(3,4) << '\n';

  return 0;
}

上面的内容比较有趣,因为没有警告,但是根据-O0-O1的不同输出:

g++ maybe-uninitialized.cpp -O0 ; ./a.out
Output: 3 != 4 (3 != 4) 

g++ maybe-uninitialized.cpp -O1 ; ./a.out
Output: 3 != 4 (0 != 0) 

编辑3-接受的答案

感谢@RyanHaining。

#include <iostream>

struct CheckEq
{
  int const& x_;
  int const& y_;
  explicit operator bool() const { return !(x_ == y_); }
};

int f() {
  std::cout << "f() called." << std::endl;
  return 3;
}

int g() {
  std::cout << "g() called." << std::endl;
  return 4;
}

#define CHECK_EQ(x, y) if (CheckEq const& check_eq = CheckEq{(x),(y)}) \
  std::cout << #x << " != " << #y \
    << " (" << check_eq.x_ << " != " << check_eq.y_ << ") "

int main() {
  CHECK_EQ(f(),g()) << '\n';
}

输出:

f() called.
g() called.
f() != g() (3 != 4) 

功能:

  • CHECK_EQ的每个参数仅被检查一次。
  • 输出显示内联代码比较和值。

2 个答案:

答案 0 :(得分:4)

该代码具有未定义的行为。调用Foo的构造函数会导致prvalue 3作为临时对象的实现,该临时对象绑定到参数x。但是,该临时对象的生存期在构造函数退出时结束,在评估x_时留下foo.x_作为悬挂引用。

您需要提供更多有关希望CHECK宏如何工作的详细信息,然后才可能提出一种无需执行此处操作就可以实现该宏的方法。

答案 1 :(得分:3)

虽然具有用户定义的构造函数的类无法延长临时an aggregate can的生存期。通过转换为汇总,我可以使您的方法有效

#include <iostream>

struct CheckEq
{
  int const& x_;
  int const& y_;
  bool const result_;
  explicit operator bool() const { return !result_; }
};

// adding () here for macro safety
#define CHECK_EQ(x, y) if (CheckEq const& check_eq = CheckEq{(x),(y),((x)==(y))}) \
  std::cout << #x << " != " << #y \
    << " (" << check_eq.x_ << " != " << check_eq.y_ << ") "

int main() {
  CHECK_EQ(3,4) << '\n';
}

对于我来说,无论是否带有-O3,都会​​产生相同的输出