简体   繁体   中英

How to guarantee that a function is inlined in C++

in C++, a function can be defined to be inline using inline key word. It is like the programmer has requested from the compiler to insert the complete body of the function in every place that the function is called.

But as I know compilers are not obligated to respect this request. So is there any way to guarantee that a function is inlined?

Nope. Actually inlining a function is a complete implementation detail, and many functions cannot be inlined. This makes the existence of an inline forcing mechanism impossible. Even compilers that offer keywords like __forceinline (VC++) won't inline functions with that qualifier under some circumstances. And the page carries a very apt warning about misusing this qualifier.

在VC ++中使用__forceinline在g ++中使用__attribute__((always_inline))

As this isn't covered by the standard, it depends on the compiler you're using. The compiler's documentation will tell you if there is a feature for forcing a function to be inlined, and how to use it. The documentation should also tell you the limits of that feature, such as for recursive calls in a non-tail position.

If you are using a Microsoft compiler, you may use __forceinline, as explained here: http://msdn.microsoft.com/en-us/library/z8y1yy88%28v=vs.71%29.aspx

I do not know of a way to force inlining in g++ or other compilers.

By putting the definition of a function right into its declaration in the header, the function gets the highest chances to be inlined.

class TheClass
{
public:
    static void DoSomething () // declaration
    {
        // the function's code (definition) goes here
    };
};

// in the same header..

void DoOtherThings () // declaration
{
    // the function's code (definition) goes here
}

In any case, there is no strong guarantee, perhaps even if you use the compiler-specific keyword for inline forcing.

A 100% percent guarantee would be transforming your function into a C++ macro and using the macro instead of referring to the function. If you function has multiple lines, place a \\ (a space followed by a backslash) where you want to have a line break in your "macro-function".

I cannot imagine that there´sa way to do that. It is mainly dependant on the compiler. Another solution would be to use #define macro to define your function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM