Compilation error if return value is not used for a specific type

I want to make compilation unsuccessful for calling any function, but not for others. The function call that I want to crash is those that do not handle return values ​​when the value is of a particular type. In the example below, not processing a function that returns Error is a compilation error, but not processing a function that returns anything else should work just fine.

Note: our runtime (built-in) does not allow us to use the following constructs: RTTI, exceptions.

This code is only needed by the compiler with Clang, I would prefer not to comment on every function.

We prefer a solution that is not executed at compile time rather than at run time.

 enum class Error { INVAL, NOERR, }; // do something that can fail. Error DoThing(); // may return different return codes, we never care (we can't change prototype) int DoIgnoredThing(); int main() { DoThing(); // compilation failure here, unused "Error" result DoIgnoredThing(); // compilation succeeds, OK to ignore unused "int" result return 0; } 
+4
source share
3 answers

I don't know how to do this with direct C ++, but if you use g ++, you can use the warn_unused_result attribute along with the command line flag -Werror = unused-result. See the documentation for warn_unused for how to specify it (you will need to specify it for each function, unfortunately, I do not believe that you can specify it for a type). Then the compiler flag will turn this warning into an error.

If you are not using g ++, your compiler may have similar functions.

+3
source

It may be easier for you to use a code analysis tool to scan the source code.

This may allow you to use the return type as you requested, or another token for functions that will be checked as a comment, to indicate which functions should be checked.

You can run the analysis tool as part of the compilation process or as part of the build server.

0
source

I tried several ways to make a class that will do what you want, but I have not been successful. Do you think your "return value" is an argument passed by reference? That the most common way that I saw the API makes you pay attention to the return value. Therefore, instead of

 Error DoThing(); 

you have

 void DoThing(Error& e); 

Everything that calls DoThing () must pass in the Error object, or they will get a compiler error. Again, not quite what you asked for, but maybe good enough?

0
source

Source: https://habr.com/ru/post/1434100/


All Articles