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?
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