【C++基础】inline函数

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的里里外外


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值