GCC 7.3 是否省略了引用返回成员函数的 [[nodiscard]] 属性?

发布于 01-18 05:58 字数 1052 浏览 2 评论 0原文

我得到了利用 C++17[[nodiscard]] 属性的以下代码。

class SomeClass {
public: /** Methods **/
    [[nodiscard]] int getValue()  { return n; }
    [[nodiscard]] int &getRef()   { return n; }
    [[nodiscard]] int *getPtr()   { return &n; }

private: /** Members **/
    int n{5};
};

int main() 
{
    SomeClass object;

    object.getValue();
    object.getRef();
    object.getPtr();

    return 0;
}

当我使用 GCC 7.3 编译它时,我收到两个警告,指出两个函数的返回值被忽略。编译器检测到的两个函数不返回引用:getValue()getPtr()

另一方面,当使用GCC 8.1及以上版本编译时,getRef()也会产生警告。

GCC 提供的 C++ 支持表显示 [从版本 7 开始完全支持 [nodiscard]] 属性。它还有一个白色的 论文

不鼓励将 [[nodiscard]] 调用作为潜在评估的丢弃值表达式出现,除非显式转换为 void。

那么,这是一个错误还是我错过了什么?

I've got the following code utilizing the [[nodiscard]] attribute of C++17.

class SomeClass {
public: /** Methods **/
    [[nodiscard]] int getValue()  { return n; }
    [[nodiscard]] int &getRef()   { return n; }
    [[nodiscard]] int *getPtr()   { return &n; }

private: /** Members **/
    int n{5};
};

int main() 
{
    SomeClass object;

    object.getValue();
    object.getRef();
    object.getPtr();

    return 0;
}

When I compile it with GCC 7.3, I've two warnings stating that the return value of two functions is ignored. The two functions detected by the compiler are the ones that don't return a reference, getValue() and getPtr().

On the other hand, when compiled with GCC 8.1 and above versions, the getRef() also causes a warning.

The C++ support table provided by GCC shows that the [[nodiscard]] attribute is fully supported as of version 7. It also has a white paper.

Appearance of a [[nodiscard]] call as a potentially ­evaluated discarded­ value expression is discouraged unless explicitly cast to void.

So, is it a bug or am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏爱你一生2025-01-25 05:58:04

是的,这是一个错误。正如您已经意识到的那样,它已在 GCC 8 中修复。

错误报告:https://gcc.gnu.org/bugzilla/show_bug.cgi ?id=80896

Yes, it is a bug. It was fixed in GCC 8 as you have already realized.

Bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80896

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文