macro
缺点:
(1)#define F (x) (x + 1)
~~多余的空格,造成的错误很难找到
(2)对于macro里的每一项都要用括号括起来,如
#define FLOOR(x,b) x>=b?0:1,如此调用
if(FLOOR(a&0x0f,0x07))....,等价于
if(a&0x0f>=0x07?0:1)...,由于>=的优先级高于&造成结果错误
(3)side effect,如
#define BAND(x) (((x)>5 && (x)<10) ? (x) : 0)
调用BAND(++a),有可能造成a自增两次,主要原因是macro只是简单
的替换,而不是真正的函数
优点:效率高!
inline function
继承macro的优点,扬弃macro的缺点,唯一不足的是,由于编译器
将inline函数放在符号表里,包括声明和函数体,占用空间,但是
因为inline函数一般都是比较简单的,这样的函数做为inline函数比
做为一般的函数使用更少的空间,因为一般的函数都需要参数的出入
栈操作以及调用CALL。
既然inline函数和macro差不多,为什么还要inline呢?
因为macro对于类的作用域没有概念,如
class X{
int i;
public:
#define VAL(X::i) //error
macro只会把X::i当作一个整体,而不知道是指类X的i
It is important to understand that an inline is just a suggestion to the compiler;
the compiler is not forced to inline anything at all. A good compiler will inline
small, simple functions while intelligently ignoring inlines that are too complicated.
This will give you the results you want – the true semantics of a function call with
the efficiency of a macro.
inline函数一般用于取得或设置私有数据的函数上,
用法:
//test.h
class test
{
int i;
public:
test(int ii=0):i(ii){}
int getData(){return i;}
//写在类内部的默认为inline
void setData();
void outData();
};
inline void test::setData()
//以inline开头,注意inline函数要写在定义类的头文件里
{
i = i * 2;
}
chap9 inline function
最新推荐文章于 2024-07-24 23:07:17 发布