gpt4 book ai didi

c++ - 如果返回类具有析构函数,则忽略 gnu::warn_unused_result 属性

转载 作者:太空狗 更新时间:2023-10-29 21:36:24 29 4
gpt4 key购买 nike

如果用户不保存某个函数的返回值,我想警告用户,但如果函数返回一个具有非默认析构函数的类,它就不起作用。

假设以下代码:

struct A {};
struct B { ~B() {} };

[[ gnu::warn_unused_result ]]
A foo() { return A{}; }

[[ gnu::warn_unused_result ]]
B bar() { return B{}; }

int main()
{
foo(); // warning
bar(); // no warning
return 0;
}

使用 g++ 6.2.1 编译时,只有 foo() 会产生警告:

$ g++ -Wall -Wextra ./test.cpp 
./test.cpp: In function ‘int main()’:
./test.cpp:13:9: warning: ignoring return value of ‘A foo()’, declared with attribute warn_unused_result [-Wunused-result]
foo();
^

我知道调用 B 的析构函数可能被认为是“结果的使用”,但问题是:

  • 这是预期的行为还是 g++ 中的错误/功能?
  • 有没有办法强制编译器在这种情况下发出警告?
  • C++17 的 [[ nodiscard ]] 的行为是否相同?

最佳答案

Is this an expected behaviour or is this a bug/feature in g++?

这是一个 QoI 问题,所有此类警告也是如此。 gcc 7 确实bar() 发出警告,因此虽然不发出警告不是错误,但它更像是 gcc 6.2 中缺少的功能。

Will C++17's [[ nodiscard ]] behave the same?

这也是实现定义的。 [dcl.attr.nodiscard]中的标准中有一个非规范的注释:

Appearance of a nodiscard call as a potentially-evaluated discarded-value expression (Clause 5) is discouraged unless explicitly cast to void. Implementations are encouraged to issue a warning in such cases. This is typically because discarding the return value of a nodiscard call has surprising consequences.

在这种情况下,不需要实现来发出警告。但他们可能会尝试这样做。

关于c++ - 如果返回类具有析构函数,则忽略 gnu::warn_unused_result 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551304/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com