Failing compilation if return value is unused for a certain type

我怕爱的太早我们不能终老 提交于 2019-12-06 05:48:27

问题


I would like to make compilation fail for some function call but not others. The function call that I want to fail are those that do not handle return values when the value is of a certain type. In the example below, not handling a function returning Error is a compilation error but not handling a function that returns anything else should succeed just fine.

Note: our runtime environment (embedded) does not allow us to use the following constructs: RTTI, exceptions.

This code only needs to compiler with Clang, I would prefer not having to annotate each function.

We prefer a solution that fails at compile time instead of at runtime.

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

回答1:


I don't know of a way to do it with straight C++, but if you're using g++ you can use the warn_unused_result attribute along with the -Werror=unused-result command-line flag. See the documentation for warn_unused result for how to specify it (you'll have to specify it on every function unfortunately; I don't believe you can specify it for a type). Then the compiler flag will turn that warning into an error.

If you're not using g++, your compiler may have similar functionality.




回答2:


You might find it easier to use a code analysis tool to scan the source code.

This might let you use the return type, as you requested, or a different marker for the functions to test like a comment to indicate which functions should be checked.

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




回答3:


I've tried a few ways to make a class that would do what you want, but I haven't been successful. Have you considered making your "return value" an argument passed by reference? That's the most common way that I've seen APIs force you to pay attention to the return value. So instead of

Error DoThing();

you have

void DoThing(Error& e);

Anything that calls DoThing() has to pass in an Error object or they will get a compiler error. Again, not exactly what you asked for, but maybe good enough?



来源:https://stackoverflow.com/questions/12416604/failing-compilation-if-return-value-is-unused-for-a-certain-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!