C++,python,热爱算法和机器学习
全部博文(1214)
分类: C/C++
2010-12-15 21:06:33
A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls!
Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed).
It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators.
关于inline函数在CPPL书中有说明,inline函数具有static的属性而不是一般函数的extern属性,就是说你在一个CPP文件里定义了一个inline函数,在别的文件里不能调用这个inline函数(它对外不可见)。所以一般都定义在Class的头文件里面,最好做成类的friend函数。而且C++对函数做成inline的形式有很多限制,并不是声明成inline函数就一定在编译器里将其展开成inline,对于返回左值的函数都不会编译成inline模式,即使你声明了它为inline,因为展开之后没有办法放在赋值符号的左边。
U should put inline functions' definations in header files.
Two form:
1. member funcions defined inside class body are auto inline, but whether they are really inlined depend on compiler.
/* person.h */ class Person { int m_age; public: ... int getAge() { return m_age; } // defination after declaration,implicit,"inline" keyword not need }
/* person.h */ class Person { int m_age; public: ... inline int getAge(); // declaration,explicit }; // also in persion.h inline int Person::getAge() { return m_age; } // defination