clang++ 8.0.1 自分配重载警告

Jak*_*ský 5 c++ compiler-warnings clang++

考虑这段代码:

class Vector {
public:
    Vector& operator+=(const Vector &v) { return *this; }
    Vector& operator-=(const Vector &v) { return *this; }
    Vector& operator*=(const Vector &v) { return *this; }
    Vector& operator/=(const Vector &v) { return *this; }
};

int main()
{
    Vector v;
    v += v;
    v -= v;
    v *= v;
    v /= v;
}
Run Code Online (Sandbox Code Playgroud)

当使用 clang++ 8.0.1 编译时,我收到以下警告:

$ clang++ -Wall example2.cpp -o example2
example2.cpp:13:7: warning: explicitly assigning value of variable of type 'Vector' to
      itself [-Wself-assign-overloaded]
    v -= v;
    ~ ^  ~
example2.cpp:15:7: warning: explicitly assigning value of variable of type 'Vector' to
      itself [-Wself-assign-overloaded]
    v /= v;
    ~ ^  ~
2 warnings generated.
Run Code Online (Sandbox Code Playgroud)

该警告试图指出什么问题?operator+=为什么and没有这样的警告operator*=

编辑:有关动机(或此类自分配表达式的实际用法),请参阅https://github.com/pybind/pybind11/issues/1893

编辑 2:我通过删除运算符中除 return 语句之外的所有内容来简化代码;同样的问题仍然发生。

Hol*_*Cat 3

这是我的猜测:

Clang 认识到对于标量 v -= v意味着v = 0.

它假设您每次使用时v -= v,都是一种奇特的表达方式v = 0

但由于v是一个重载的类-=,它会警告您在这种情况下v -= v可能不等于v = 0

它对 执行相同的操作v /= v,因为它相当于v = 1标量(除非v == 0)。


如果我的推理是正确的,那么在我看来,这是一个非常愚蠢的警告。

我宁愿对标量发出警告v -= v;v /= v;使用它。