tags:

views:

858

answers:

12

Main Question

When should I write the keyword 'inline' for a function/method in C++?


Edit:

Questions added by seeing some answers...

  • When should I not write the keyword 'inline' for a function/method in C++?

  • When will the the compiler not know when to make a function/method 'inline'?

  • Does it matter if an application is multithreaded when one writes 'inline' for a function/method?

+7  A: 

1) Nowadays, pretty much never. If it's a good idea to inline a function, the compiler will do it without your help.

2) Always. See #1.

(Edited to reflect that you broke your question into two questions...)

Aric TenEyck
Yes. The inline is only a hint to the compiler, and it is free to ignore you. These days the compiler probably knows better than the programmer which functions are best to inline.
Mark Byers
This is true for C as well, correct?
Benjamin Oakes
Yes, but it's less relevant - for a function to be inlined, it's body must be in the same compilation unit (for instance, in a header). That's less common in C programs.
Michael Kohne
While the compiler can do a good job today, do you know of any cases when you should write it?
Partial
defining a non-member function template (aka non-static function template) does not require inline. See one definition rule(3.2/5).
caspin
A: 

The inline function would have to be very short and simple and you would need to be very certain that making it an inline function would be of some performance benefit. I would never use the word inline until I had real data that showed that there would be a benefit to making it inline. I would test it both before and after to verify that the "inline" optimization was of benefit.

Modern C++ Compilers are very very good at optimization. Usually they can figure out what to do without hints like "inline".

On more careful consideration if you need to define a function in a header file, or a function in more than one header file - if you make the function "inline" it will not cause link errors. If the function is not inline then you will have copies of the function in multiple files and get link errors.

Philip Schlump
I did not say where...
Partial
When, not where.
Mark Byers
Sorry - my bad - I did not read the question carefully.
Philip Schlump
+4  A: 

In reality, pretty much never. All you're doing is suggesting that the compiler make a given function inline (e.g., replace all calls to this function /w its body). There are no guarantees, of course: the compiler may ignore the directive.

The compiler will generally do a good job of detecting + optimizing things like this.

DarkSquid
The problem is that `inline` has a _semantic_ difference in C++ (e.g. in the way multiple definitions are treated), which is important in some cases (e.g. templates).
Pavel Minaev
inline is used to resolve cases where a symbol has multiple definitions. Templates however are already handled by the language. One exception is a specialized template function that doesn't have any template paramters anymore (template<>). These are treated more like functions than templates and so need the inline keyword in order to link.
caspin
+2  A: 

When it is a [typically short] function which is going to be called in "tight" (read performance sensitive) loops.

This said, several compilers will decide when it is good to inline and will just do this for you... Some of the compiler's command line options may "help" it be more or less aggressive with the amount of inline that is done.

mjv
A: 

when the method is small and you want to avoid the overhead cost of a function call.

See item #30 in Effective C++

Holograham
+1  A: 

You want to put it in the very beginning, before return type. But most Compilers ignore it. If it's defined, and it has a smaller block of code, most compilers consider it inline anyway.

Jeremy Morgan
+3  A: 

When developing and debugging code, leave inline out. It complicates debugging.

The major reason for adding them is to help optimize the generated code. Typically this trades increased code space for speed, but sometimes inline saves both code space and execution time.

Expending this kind of thought about performance optimization before algorithm completion is premature optimization.

wallyk
+1: Very true indeed.
Partial
`inline` functions are typically not inlined unless compiling with optimizations, so they do not affect debugging in any way. Remember that it's a hint, not a demand.
Pavel Minaev
gcc by default does not inline any functions when compiling without optimization enabled. I don't know about visual studio
caspin
I worked on an enormous g++ project which had debugging enabled. Maybe other options prevented it, but the `inline` functions were inlined. It was impossible to set a meaningful breakpoint in them.
wallyk
enabling debugging doesn't stop inlining in gcc. If any optimization where enabled (-O1 or greater), then gcc will try to inline the most obvious cases. Traditionally GDB has had a hard time with breakpoints and constructors especially inline constructors. But, that has been fixed in recent versions (at least 6.7, maybe sooner).
caspin
Adding `inline` will do nothing to improve the code on a modern compiler, which can figure out whether to inline or not on its own.
David Thornley
+2  A: 

You still need to explicitly inline your function when doing template specialization (if specialization is in .h file)

BostonLogan
wow, didn't know about that one. I had to look it up an play with the compiler for a bit before I believed you.
caspin
+3  A: 

The primary you want to use the inline keyword is with templates. With most compilers templates have to be in a header so they're visible in all files that use them. If you instantiate your template with the same parameter in more than one translation unit, and use the same function in both, you've just defined the same function twice -- violating the one definition rule.

Making the function inline cures that problem. You can do this either by defining the function inside the class template definition, or by placing it outside the class definition, but explicitly marking it inline. I generally define the function inside the class definition if it's really short (especially one-liners) but move it out of the class definition if it's very long at all.

Edit: It is true that the standard makes some concessions to allow multiple definitions of template instantiations (for one example), but you have to be extremely careful: it takes almost an entire page to describe the conditions that must be met for such a multiple definition to be allowed. One of those requirements is that:

If D is a template, and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2).

When you're writing template code, you generally know next to nothing about the dependent names at the point of instantiation. Worse, you generally don't want to know such things. In most cases, the whole point of a template is that a user should be able to instantiate it over any type that meets a few specific requirements (that, in an ideal world, you'd have expressed in concepts, R.I.P.)

Since your template code can't depend on those requirements being met, the reasonable alternative is to assure that they don't have to be met -- and making all the functions inline is a big start toward that.

Jerry Coffin
+1 Nice to know that for templates!
Partial
This is wrong. Template functions never need to be inlined the linker already knows they're special.
caspin
@Caspin, I believe you're confusing some things. If you have two .cpp files containing code for an instantiation of the same function template (because they both included the same .h file with a template definition, and used it in the same way), it is ill-formed, because such instantiation has external linkage (see ISO C++03 3.5[basic.link]/2-4) and therefore must conform to One Definition Rule (3.2[basic.def.odr]). The compiler is not required to issue a diagnostic, but _may_ do so, and in any case the behavior is undefined.
Pavel Minaev
In contrast, when a function with the same name (this includes template instantiations) is marked `inline` in two different translation units, so long as the definition is exactly the same, the compiler is _required_ to compile this.
Pavel Minaev
I hold to my original statement. Templates do not need inline in order for the linker to treat them as inline. I am scouring the standard now looking for some section numbers to back me up. If I am wrong I know that Visual Studio, Gcc, Intel CC all implement this extension.
caspin
The one definition rule (3.2/5) makes explicit concessions for templates(among other things). <quote> There can be more than one definition of a class type, enumeration type, inline function withexternal linkage, class template, non-static function template, static data member of a class template, member function of a class template, ... </quote>
caspin
I'm surprized to see two respectable C++ programmers (Jerry Coffin and Pavel Minaev) getting the one-definition-rule wrong. The ODR clearly allows multiple definitions of inline functions, function templates, classes and static data members of class templates as long as they appear in different translation units.
sellibitze
You are indeed correct that I've got ODR rule regarding templates wrong. However, it seems that it is extremely easy to violate ODR limitations for templates, because they recursively apply to all dependent names, and the latter are looked at the point of instantiation: "If D is a template, and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2)."
Pavel Minaev
@Pavel, @Jerry, but the point here is, the `inline` keyword will do *nothing* regarding this - you still have only *one* template, and *multiple* definitions, that all have to adhere to the ODR. No matter whether you declared them inline - `inline` won't change the linkage of a function, it stays extern/internal.
Johannes Schaub - litb
+1  A: 

When one should inline :

1.When one want to avoid overhead of things happening when funtion is called like parameter passing , control transfer, control return etc..

2.The funtion should be small,frequently called and making inline is really advantageous since as per 80-20 rule,try to make those funtion inline which has major impact on program performance.

As we know that inline is just a request to compiler similar to register and it will cost you at Object code size.

Ashish
+35  A: 

Oh man, one of my pet peeves.

inline is more like static or extern than a directive telling the compiler to inline your functions. extern, static, inline are linkage directives, used almost exclusively by the linker, not the compiler.

It is said that inline hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.

static the variable/function name cannot be used in other compilation units. Linker needs to make sure it doesn't accidentally use a statically defined variable/function from another compilation unit.

extern use this variable/function name in this compilation unit but don't complain if it isn't defined. The linker will sort it out and make sure all the code that tried to use some extern symbol has its address.

inline this function will be defined in multiple compilation units, don't worry about it. The linker needs to make sure all compilation units use a single instance of the variable/function.

Note: Declaring templates inline is worthless. They have the linkage semantics of inline already.


So specific answers to your questions:

  • When should I write the keyword 'inline' for a function/method in C++?

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 compilation 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. It also increases compilation time.

  • When should I not write the keyword 'inline' for a function/method in C++?

Don't add inline when you think your code will run faster if the compiler inlines it.

  • When will the the compiler not know when to make a function/method 'inline'?

Generally the compiler will be able to do this better than you. However, the compiler doesn't have the option to inline code if it doesn't have the function definition. In maximally optimized code usually all private methods are inlined whether you ask for it or not.

As an aside to prevent inlining in GCC use __attribute__(( noinline )) and in visual studio use __declspec(noinline).

  • Does it matter if an application is multithreaded when one writes 'inline' for a function/method?

Multithreading doesn't affect inlining in anyway.

caspin
+1 Best description of inline I have seen in ... (forever). I will now rip you off and use this in all my explanations of the inline keyword.
Martin York
A: 

the one said that inlining functions has to do only with linker is fundamentally wrong. When the compiler inserts inlined function into the main function body it does a pretty decent job of reorganizing data flow thru general use registers and stack. If it just inserted the function body as it is with pushing registers to stack and getting them back - that wouldn't make any sense, cause this idea is opposite to the inlining.

Alexander Solonsky