![](/img/trans.png)
[英]Does GCC 7.3 omit the [[nodiscard]] attribute for reference returning member functions?
[英]Is GCC correct to ignore the nodiscard attribute on overridden member functions?
由于这个问题和答案,属性是否被继承并不是 100% 清楚,但可能不是,因为标准中没有说明。 这就是为什么如果我们在基础 class 中只有标记为nodiscard
的声明,并使用 Clang 进行编译,我们只有在使用“基础”指针访问 object 时才会收到警告。
以下代码的问题在于,在使用 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 中的一种错误(不太可能,因为编译器资源管理器中可用的每个版本,从 8.1 到 11.1,都会产生相同的结果),还是我做错了什么?
对我来说,这似乎是一个错误,因为它适用于 Clang。 但是这个bug需要2个条件才能触发:
virtual
方法unique_ptr
可以做到。 如果你得到一个简单的实例并直接调用 function,你会看到警告。但是,如果您需要解决方法,您可以使用另一个属性。 这是一个小样本:
struct A{
[[gnu::warn_unused_result]]
virtual int foo() {
return 1;
}
};
int main(){
A a;
a.foo();
}
此属性适用于 GCC 和 Clang。
另一个建议:您可以使用[[nodiscard, gnu::warn_unused_result]]
类的属性,这适用于所有编译器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.