Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use __forceinline instead of inline?

Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states:

The __forceinline keyword overrides the cost/benefit analysis and relies on the judgment of the programmer instead.

This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am I supposed to know that it's wrong?

In what scenario is it assumed that I know better than my compiler on this issue?

like image 771
Michael Labbé Avatar asked Sep 30 '08 05:09

Michael Labbé


People also ask

What does __ Forceinline do?

The __forceinline keyword forces the compiler to compile a C or C++ function inline. The semantics of __forceinline are exactly the same as those of the C++ inline keyword.

When inline method should not be used?

When we should avoid the use of inline? We should not use functions that are I/O bound as inline functions. When large code is used in some function, then we should avoid the inline. When recursion is used, inline function may not work properly.

When should we declare a functions as inline?

Only when you want the function to be defined in a header. More exactly only when the function's definition can show up in multiple translation units. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code.

When might a compiler choose not to inline a function declared as inline?

The compiler can't inline a function if: The function or its caller is compiled with /Ob0 (the default option for debug builds). The function and the caller use different types of exception handling (C++ exception handling in one, structured exception handling in the other). The function has a variable argument list.


2 Answers

You know better than the compiler only when your profiling data tells you so.

like image 111
Don Neufeld Avatar answered Oct 09 '22 00:10

Don Neufeld


The one place I am using it is licence verification.

One important factor to protect against easy* cracking is to verify being licenced in multiple places rather than only one, and you don't want these places to be the same function call.


*) Please don't turn this in a discussion that everything can be cracked - I know. Also, this alone does not help much.

like image 24
peterchen Avatar answered Oct 08 '22 22:10

peterchen