gpt4 book ai didi

c++ - 警告 : ‘’ is used uninitialized in this function [-Wuninitialized]

转载 作者:太空狗 更新时间:2023-10-29 20:08:14 24 4
gpt4 key购买 nike

以下程序使用 -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 的每个参数只检查一次。
  • 输出显示内联代码比较以及值。

最佳答案

代码有未定义的行为。调用 Foo 的构造函数会导致纯右值 3 物化为临时对象,该对象绑定(bind)到参数 x。但是当构造函数退出时,该临时对象的生命周期结束,在评估 foo.x_ 时将 x_ 作为悬空引用。

您需要提供更多关于您希望您的 CHECK 宏如何工作的详细信息,然后才能建议一种无需执行您在此处所做的操作即可实现它的方法。

关于c++ - 警告 : ‘<anonymous>’ is used uninitialized in this function [-Wuninitialized],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55976434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com