捕获未分配的 r 值的编译器选项

Compiler option to catch unassigned r-values

相当尴尬,我写了类似下面的东西(经过消毒):

vector_item next()
{
    if (this->it == this->myVector.end()){
        this->it == this->myVector.begin();
    }
    return *(this->it++);
}

明显的错误是非常明显的。然而,它确实需要一段时间才能找到。

没有为此生成编译器警告,但应该生成一个吗?这里创建了一个未使用的 r 值(不是说,一个未使用的 return 值来自一个函数,该值被称为其副作用),在我看来这表明代码。

使用 g++ -Wall -Wextra 编译。 (海湾合作委员会 4.8.3)

我知道 -Wunused-result 但这不适用于此处。

No compiler warnings were generated for this, but should one have been?

我想不出我在标准中读到的任何内容需要在此处发出警告。

然而,clang 开发团队似乎认为它值得一个:

18 : <source>:18:18: warning: equality comparison result unused [-Wunused-comparison]
        this->it == this->myVector.begin();
        ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
18 : <source>:18:18: note: use '=' to turn this equality comparison into an assignment
        this->it == this->myVector.begin();
                 ^~
                 =
1 warning generated.

我的第一个想法是这是 gcc 中的 QoI 问题。可能值得将其作为一个问题提出。

我很幸运,因为我们的软件是为 mac (clang)、linux (gcc) 和 windows (msvc) 编译的,因此可以及早发现违反标准的情况和边缘情况.

在不时地进行错误搜索之前,在另一个编译器上重新编译您的代码可能是个好主意 - 它对我有帮助。

No compiler warnings were generated for this, but should one have been?

标准中没有声明任何应该让 GCC 为这种情况生成警告的内容。

您可以通过将其标记为 WARN_UNUSED 来扩展 begin(),首先您将定义:

#define WARN_UNUSED __attribute__((warn_unused_result))

here 所述,但这当然不是您要找的东西,但确实是这样。我找不到 GCC 的任何选项来生成针对您的情况的警告。

它是已知的 GCC bug though, but hasn't implemented 您正在寻找的功能,至少在 2017 年 7 月 21 日之前是这样。


但是,clang 6.0.0 对此发出警告,(即使未使用 WallWextra 标志):

prog.cc:11:18: warning: equality comparison result unused [-Wunused-comparison]
        this->it == this->myVector.begin();
        ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
prog.cc:11:18: note: use '=' to turn this equality comparison into an assignment
        this->it == this->myVector.begin();
                 ^~
                 =
1 warning generated.

此外,zapcc 1.0.1 也会发出警告(即使没有警告标志):

/home/jail/prog.cc:11:18: warning: equality comparison result unused [-Wunused-comparison]
        this->it == this->myVector.begin();
        ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
/home/jail/prog.cc:11:18: note: use '=' to turn this equality comparison into an assignment
        this->it == this->myVector.begin();
                 ^~
                 =
1 warning generated.

如果喜欢,请在 Wandbox 中自行查看。