Failing compilation if return value is unused for a certain type

☆樱花仙子☆ 提交于 2019-12-04 12:19:06

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.

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.

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?

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