Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading