__attribute__系列之__attribute__((always_inline))

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() 
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值