Google C++ 编程规范 1.3

来源:岁月联盟 编辑:猪蛋儿 时间:2012-11-16

Inline Functions

内联函数

▽Define functions inline only when they are small, say, 10 lines or less.

只有函数非常小,10行以内才定义为内联。

Definition:  You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism.

定义:一种函数调用机制,你将函数声明为内联,编译器会将整个函数体在调用处展开。

Pros:  Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions.

前题条件:当内联一个很小函数时会产生更有效率的代码,考虑类成员访问函数或其他短小,性能要求严格的函数。

Cons:  Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache.

限制:过度使用内联函数实际上会使减慢程序运行,取决于函数体大小,它决定了代码增加或减少。内联一个非常小成员访问函数会减少代码,而内联一个非常大的函数代码会戏剧性的增长。在现代处理器上由于广泛使用指令缓存,小代码通常会运行得更快。

Decision:

决策:

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!

一个合适的经验法则:不要内联一个超过10行函数,但要小心析构函数,它并没有表面看上去那么小,因为它会调用类成员和基类的析构函数。 www.2cto.com

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.

知道哪些函数即使你声明了内联也不会内联很重要:比如说虚函数和递归函数在一般情况下不会内联。通常情况下递归函数不应内联。使虚函数内联的主要原因在于类定义,主要是方便的原因,比如说成员访问函数。


 

下一篇:error C2248