Can a C++ function be declared such that the return value cannot be ignored?

后端 未结 4 1395
青春惊慌失措
青春惊慌失措 2020-12-29 20:52

I\'m trying to determine whether a C++ function can be declared in such a way that the return value cannot be ignored (ideally detected at compile time). I tried to declare

4条回答
  •  醉梦人生
    2020-12-29 21:41

    See __attribute__ ((warn_unused_result)).

    int foo() __attribute__ ((warn_unused_result));
    int foo(){return 123;}
    
    int main()
    {
        foo(); //compiler warning
        auto i = foo(); //valid
    }
    

    Then force the warning to be an error:

    clang++ -std=c++1z -Werror="unused-result"
    

提交回复
热议问题