Inline 函数

来源:互联网 发布:python 数据库 编辑:程序博客网 时间:2024/04/28 12:17

最近看代码常常把代码编译好看汇编结果,所以有机会更近的接触下inline。

Inline的好处,effective c++讲了一堆,当然是能用则用了。

这里就说下一些细节的东西。

inline是编译时刻嵌入的,在gcc的preprocess结果来看,inline并没有展开,在编译 时刻inline做了展开,在优化模式下,inline就像直接写入的代码一样,执行顺序会被编译器优化和上下文的代码参杂起来。

所以既然没有调用linker,那么如果inline函数的实现在编译时刻不可见就没法做到,在vc2005和gcc中都遇到undefined reference/symbol 的错误。

所以只要在同一个编译单元就可以。可以放在.h文件中,如果inline函数只在一个.cpp中使用,那么放在同一个.cpp中也是可以的,反正一个编译单元可见就行。

class InlineTest
{
    inline 
void Test()
    
{
         
//this will inline, but too ugly
    }

}
;

 

class InlineTest
{
    inline 
void Test();
}


void InlineTest::Test() 
{
    
//this is better, but one change will bring too much compilation
}

 

 

InlineTest.h:

class InlineTest
{
    inline 
void Test();
}
;

//---------------------------------------------------------------------------------------------------------------------------------------
InlineTest.cpp:

void InlineTest::Test()
{
    
//this is pretty good, but have restriction, the function must be used in InlineTest.cpp, no where else.
}
原创粉丝点击