I’ve always wondered, if it’s good or bad practice to define trivial method twice, depending
if the project’s on debug / release -state. This is for inlining them. For instance, Foo.h:
class Foo
{
public:
...
const bool& IsBoolean() const;
private:
bool _boolean;
};
#ifndef _DEBUG
/** We're in release, so let's advice compiler to inline this...
*
*
*/
inline const bool& Foo::IsBoolean() const
{
return _boolean;
}
#endif
And now, in Foo.cpp:
#include "Foo.h"
...
#ifdef _DEBUG
/** We're debugging this, no need for inlining...
*
*
*/
const bool& Foo::IsBoolean() const
{
return _boolean;
}
#endif
Is this completely useless? For example due to compiler’s (MSVC) ability to inline / optimize methods all by itself?
Nevertheless, this is something I’ve been using for years now. Please correct me, if I’m completely wrong here…
It’s a waste of time, for several reasons.
The inline keyword is a hint that the compiler may ignore at will. Just like it is free to inline even if the keyword is not specified. So whether or not you add it probably won’t change anything for the compiler
Further, any functions defined inside the class definition are implicitly inlined. That is why short functions like getters and setters are almost always defined inside the class definition.
Next, if you want to mark a function as inline, there’s no reason not to do it in debug builds as well.
The
inlinekeyword has almost nothing to do with the compiler actually inlining functions. They are separate concepts. A function markedinlineby the programmer means that the linker shouldn’t worry if it sees multiple identical definitions. That typically happens if the function is defined in a header, which gets included into multiple compilation units. If the function is marked inline, the linker will merge the definitions together. If it isn’t, you get an error. In other words, adding and removing this keyword will cause compiler errors. That’s probably not what you want.The only reason there is a bit of overlap between the C++
inlinekeyword and the compiler optimization is that if a function is markedinline, it is safe to #include it in every compilation unit, which means the definition will always be visible when the function is called. And that makes it easire for the compiler to inline calls to the function.Finally, inlining is not always a performance improvement. It is easy to create a situation where inlining does nothing more than make the code size explode, cause more cache misses, and overall, slow down your code. That is one of the reasons why
inlineis (at best) treated as a hint by the optimizer. At worst, it is ignored entirely.So what you’re doing will 1) cause compiler errors in debug mode that didn’t exist in release builds, and 2) have no effect on performance.