No warning message generated by g++ when using [[nodiscard]] and compile with lower stl option

is there nodiscard attribute available in c++11? If not, why no warning message output by g++

code belows.

//test.cpp
#include<iostream>

[[nodiscard]] int foo() {
  return 1;
}

int main() {
  std::cout<<foo()<<std::endl;
  return 0;
}

At the beginning, i complie the program by "g++ -std=c++20 test.cpp -o test.o" and everythings is fine.

But then i want to see what the exact version that g++ can not support the attribute [[nodiscard]]. So i change the complier option to "g++ -std=c++11 -Wall test.cpp -o test2.o" and no error message output by g++ and test2.o works well.

According to chatgpt, warning message will shown at 8.1 gcc version and my gcc version is 11.3.0.

I wonder if it is because of the Updated version gcc have made some update which allows lower version of c++ stl support it? Or for other reasons?

>Solution :

[dcl.attr.grammar]/6 states that

For an attribute-token (including an attribute-scoped-token) not specified in this International Standard, the behavior is implementation-defined. Any attribute-token that is not recognized by the implementation is ignored. [ Note: Each implementation should choose a distinctive name for the attribute-namespace in an
attribute-scoped-token. —end note ]

So, if you’re using a standard, or implementation, prior to [[nodiscard]] being supported, it will just be ignored (so long as the standard is new enough to at least recognize an attribute (C++11))

[dcl.attr.nodiscard]/2 states

Appearance of a nodiscard call as a potentially-evaluated discarded-value expression is discouraged unless explicitly cast to void. Implementations are encouraged to issue a warning in such cases.

In your code, the result of foo() is not discarded; it is used in the output of std::cout<<foo()<<std::endl;.

Leave a Reply