【C++基础】inline函数
2014-02-05 16:42
363 查看
1. 为什么使用inline
在大多数机器上,调用函数都要做很多工作:调用前要先保存寄存器,并在返回时恢复,复制实参,程序还必须转向一个新位置执行.使用内联函数可以避免函数调用的开销.
内联说明对于编译器来说只是一个建议,编译器可以选择忽略这个建议.
2.内联函数定义
内联函数的定义对编译器而言必须是可见的,以便编译器能够在调用点内联展开该函数的代码.此时,仅有函数原型是不够的.内联函数可能要在程序中定义不止一次,只要内联函数的定义在某个源文件中只出现一次,而且在所有源文件中,其定义必须是完全相同的.把内联函数的定义放在头文件中,可以确保在调用函数时所使用的定义时相同的,并且保证在调用点该函数的定义对编译器可见.
内联函数的应该在头文件中定义(建议).
3. 类中的内联函数
在类内部定义的成员函数,将自动作为inline处理.可以在类定义体内部制定一个成员为inline,作为其声明的一部分.或者,也可以在类定义体外部的函数定义上指定inline.在声明和定义处指定inline都是合法的.
不在类定义体内定义的inline成员函数,其定义通常放在有类定义的同一个头文件中.
class Screen { public: typedef std::string::size_type index; // implicitly inline where defined inside the class declaration char get() const {return contents[curosr];} // explicitly declared as inline, willl be defined outside the class declaration inline char get(index ht, index wd) const; // inline not specified in class declaration, but can be defined inline later index get_curosr() const; }; // inline declared in the class declaration; no need to repeat on the definition char Screen::get(index r, index c) cosnt { index row = r* width; return contents[row + c]; } // not declared as inline in the class declaration, but ok to make inline in definition inline Screen::index Screen:get_cirsot() const { return cursor; }
参考:Effective C++, 条款30: 透彻了解inlining的里里外外
相关文章推荐
- C/C++基础(三)【sizeof && inline函数】
- C++基础学习教程(六)----类编写的前情回顾以及项目实战(1)
- C/C++基础知识备忘录(一)----指针
- C++程序设计基础
- ROS_Kinetic_11 ROS程序基础Eclipse_C++(二)
- C++基础4:构造函数、析构函数、拷贝构造函数、静态成员函数
- C++基础摘要
- C++基础:C++中vector使用简介
- c++基础2
- c++基础:重载,模板
- C++语法基础--句柄类
- c++模板与泛型编程基础
- C/C++ 网络编程3: 套接字基础
- C++基础之三大特性之继承的本质(要当就当富二代,否则自己动手才能丰衣足食)
- C++ collection容器基础知识
- 基础排序:单元,冒泡,分治排序的C++实现与讨论
- C++基础教程(三)——枚举enum
- 强制类型转换运算符—C++基础篇
- c++基础知识
- [C++基础]029_C++学习之路