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

后端 未结 4 1527
青春惊慌失措
青春惊慌失措 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:57

    To summarize from other answers & comments, basically you have 3 choices:

    1. Get C++17 to be able to use [[nodiscard]]
    2. In g++ (also clang++), use compiler extensions like __wur (defined as __attribute__ ((__warn_unused_result__))), or the more portable (C++11 and up only) [[gnu::warn_unused_result]] attribute.
    3. Use runtime checks to catch the problem during unit testing

    If all of these 3 are not possible, then there is one more way, which is kind of "Negative compiling". Define your Unignorable as below:

    struct Unignorable {
      Unignorable () = default;
    #ifdef NEGATIVE_COMPILE
      Unignorable (const Unignorable&) = delete;  // C++11
      Unignorable& operator= (const Unignorable&) = delete;
      //private: Unignorable (const Unignorable&); public:  // C++03
      //private: Unignorable& operator= (const Unignorable&); public: // C++03
      /* similar thing for move-constructor if needed */
    #endif
    };
    

    Now compile with -DNEGATIVE_COMPILE or equivalent in other compilers like MSVC. It will give errors at wherever the result is Not ignored:

    auto x = foo();  // error
    

    However, it will not give any error wherever the result is ignored:

    foo(); // no error
    

    Using any modern code browser (like eclipse-cdt), you may find all the occurrences of foo() and fix those places which didn't give error. In the new compilation, simply remove the pre-defined macro for "NEGATIVE_COMPILE".

    This might be bit better compared to simply finding foo() and checking for its return, because there might be many functions like foo() where you may not want to ignore the return value.

    This is bit tedious, but will work for all the versions of C++ with all the compilers.

提交回复
热议问题