test.cc: In function ‘int main(int, char**)’: test.cc:15:9: warning: ignoring return value of ‘int func()’, declared with attribute nodiscard [-Wunused-result] 15 | func(); | ~~~~^~ test.cc:8:19: note: declared here 8 | [[nodiscard]] int func(void) { |
此属性可以用于有返回错误状态的函数,以告知用户不要忽略函数的返回。
c++ 20 及以后,可以在
[[nodiscard]]中加入提示的字符:
1 2 3 4 5 6 7 8 9 10 11
[[nodiscard("Hello")]] intfunc(void){ return0; }
intmain(int argc, char* argv[]){
func();
return0; };
编译将会输出:
1 2 3 4 5 6
main.cpp: In function 'int main(int, char**)': main.cpp:15:10: warning: ignoring return value of 'int func()', declared with attribute 'nodiscard': 'Hello' [-Wunused-result] 15 | func(); | ~~~~^~ main.cpp:8:29: note: declared here 8 | [[nodiscard("Hello")]] int func(void) {