attribute((always_inline)) 特性
attribute((always_inline))的意思是强制内联,有些时候编译器拒绝将inline声明的函数作为内联函数,加上__attribute__((always_inline))以后可以强制将函数声明为内联函数,使该函数在调用时直接访问其函数体内容,而不用走函数调用流程,避免上下文的切换。
直接使用inline 声明内联函数
代码演示:
#include <iostream>
#include <string>
using namespace std;
inline void test()
{
cout<<"global func"<<endl;
}
class A {
public:
A(string name):name_(name)
{
cout<<"construct func: "<<name_<<endl;
}
~A()
{
cout<<"destruct func~: "<<name_<<endl;
}
void testFunc()
{
cout<<"A::func"<<endl;
}
void Func()
{
cout<<"test func begin"<<endl;
test();
testFunc();
cout<<"test func end"<<endl;
}
private:
string name_;
};
int main()
{
A data("ketty");
data.Func();
return 0;
}
编译:
@ubuntu:~/test$ g++ -o test1 test1.cpp
查看结果:
@ubuntu:~/test$ nm test1 |grep "test"|c++filt
0000000000001406 W test()
000000000000151e W A::testFunc()
添加__attribute__((always_inline))以后:
代码演示:
#include <iostream>
#include <string>
using namespace std;
__attribute__((always_inline)) inline void test()
{
cout<<"global func"<<endl;
}
class A {
public:
A(string name):name_(name)
{
cout<<"construct func: "<<name_<<endl;
}
~A()
{
cout<<"destruct func~: "<<name_<<endl;
}
void testFunc()
{
cout<<"A::func"<<endl;
}
void Func()
{
cout<<"test func begin"<<endl;
test();
testFunc();
cout<<"test func end"<<endl;
}
private:
string name_;
};
int main()
{
A data("ketty");
data.Func();
return 0;
}
查看结果:
@ubuntu:~/test$ nm test1 |grep "test"|c++filt
00000000000014ea W A::testFunc()