Chinaunix首页 | 论坛 | 博客
  • 博客访问: 828443
  • 博文数量: 330
  • 博客积分: 9641
  • 博客等级: 中将
  • 技术积分: 3181
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
文章分类

全部博文(330)

文章存档

2012年(17)

2011年(135)

2010年(85)

2009年(57)

2008年(36)

我的朋友

分类: C/C++

2010-12-15 21:06:33


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!

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 }
2. member functions declared in class body, but defined outside class body can be inlined by prefixing "inline" keyword. 
代码:
/* 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

推荐:


友元函数也能被定义在类的内部,如果它们在那里,它们也被隐式地声明为 inline。
模板实例化与 inline 化无关(模板编译期实例化更为普遍),模板不要inline。
构造函数和析构函数的inline,是一个比能见到要糟糕的想法。因为编译器会加入大量的异常判断。
inline函数无法调试,因为他们不在那里。

阅读(587) | 评论(0) | 转发(0) |
0

上一篇:c++笔记

下一篇:vector内存管理

给主人留下些什么吧!~~