【发布时间】:2021-08-23 18:09:52
【问题描述】:
由于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,都会产生相同的结果),还是我做错了什么?
【问题讨论】:
-
对我来说,这似乎是一个 GCC 错误。 Clang 工作正常。
标签: c++ gcc attributes language-lawyer compiler-bug