如何将多行代码的内联函数视为单行?

Gan*_*ala 0 c++ inline-functions

我有一个想法,如果代码片段很小,使用“inline 关键字”全局定义内联函数(普通函数)可以提高性能。我有一个疑问:“类内部定义的成员函数如何也提供相同的性能并被视为内联? ”

小智 6

实际上内联函数包含一行代码

这种说法是错误的。不存在这样的限制。

内联函数仅仅意味着所有函数定义代码都直接放置在声明它的位置。

但是类内部定义的成员函数包含多个代码,而不是被视为内联,为什么?

如果您指的是inline关键字,则也没有限制用该关键字标记的函数只能包含一行代码。

如果它实际上由编译器内联(即直接插入到位的汇编代码,无需函数调用),则由其决定,并且主要取决于优化标志中选择的编译器优化策略。


inline如果非类成员函数完全定义在头文件中,则需要为它们提供关键字,以避免 ODR 违规错误。

这是一个示例(假设是头文件):

class foo {
    int x_;

public:
     // Inside the class declaration 'inline' is assumed as default
     int x() const { return x_; }
     int y() const {
         int result = 0;
         // Do some complicated calculation spanning 
         // a load of code lines
         return result;
     }
};

inline int bar() { // inline is required here, otherwise the compiler
                   // will see multiple definitions of that function
                   // in every translation unit (.cpp) that includes
                   // that header file.
    return 42;
}
Run Code Online (Sandbox Code Playgroud)