GCC 忽略重写成员函数上的 nodiscard 属性是否正确?

时间:2021-06-06 11:07:03

标签: c++ gcc attributes language-lawyer compiler-bug

由于 this 问题和答案,属性是否被继承并不是 100% 清楚,但可能不是,因为它没有在标准中说明。这就是为什么如果我们在基类中只有标记为 nodiscard 的声明,并使用 Clang 进行编译,我们只会在使用“基”指针访问对象时收到警告。

以下代码的问题在于,在使用 GCC(版本 8.1 到 11.1)进行编译时,它根本不发出警告。 nodiscard 仅在 Child1 中,在两个类中,或仅在 Base 中,通过 Base 指针或 Child1 指针调用,所有这些都不会帮助。

#include <memory>

class Base {
public:
    [[nodiscard]] 
    virtual int getIdentifier() const = 0;
};

class Child1 : public Base {
public:
    [[nodiscard]]
    int getIdentifier() const override {
        return 1;
    }
};

int main()
{
    std::unique_ptr<const Child1> p1 { new Child1 };
    p1->getIdentifier();

    std::unique_ptr<const Base> p2 { new Child1 };
    p2->getIdentifier();
}

这是 GCC 中的某种错误吗(不太可能,因为 Compiler Explorer 中的每个可用版本,从 8.1 到 11.1,都会产生相同的结果),还是我做错了什么?

1 个答案:

答案 0 :(得分:4)

对我来说这似乎是一个错误,因为它适用于 Clang。但是这个bug需要2个条件才能触发:

  1. <script type="module" src="/dist/page.js"></script> 方法
  2. 间接寻址。在您的情况下,page 会这样做。如果你得到一个简单的实例并直接调用函数,你会看到警告。

但是如果您需要解决方法,您可以使用另一个属性。这是一个小样本:

virtual

此属性适用于 GCC 和 Clang。

另一个建议:您可以使用像 unique_ptr 这样的属性,这适用于所有编译器。

相关问题