您的位置:首页 > 编程语言 > C语言/C++

【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的里里外外
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: