I have been reading more on C++ 20, and recently noticed the [[likely]] or [[unlikely]] attributes. Which seems like an interesting concept, not found in previous versions of C++. According to the official CPP Reference:
Allow the compiler to optimize for the case where paths of execution including that statement are more or less likely than any alternative path of execution that does not include such a statement.
What does this really imply?
This blog post, argues against using them because it seems more like pre-mature form of optimization and a few other details. https://blog.aaronballman.com/2020/08/dont-use-the-likely-or-unlikely-attributes/
EDIT: The intention with this question, is besides to learn and understand for myself and others out there, to trigger a discussion. A discussion that provides reasonable use cases for where it absolutely makes sense from an optimization and efficient programming to use these instructions.
>Solution :
It’s meant to let the compiler know which path is the "fast path", as in "more likely to happen".
For example, imagine implementing vector::at. This function throws if the index is out of bounds. But you expect this situation happen very rarely, most of the time you expect the users to access a valid element. You can mark the throwing path [[unlikely]] and the compiler will understand your intention and might optimize the program accordingly.