__attribute__

今天和同事讨论babeltrace的时候,一直找不到新format库的入口,后来仔细查找了一下已有的格式转换ctf-text的注册函数定义:void __attribute__((constructor)) ctf_text_init(void),发现了这个有趣的使用方法: __attribute__((constructor))这个东东类似于C++的构造函数,在main()前被调用. 类似的还有__attribute__((destructor))。 下面是一个网上搜索到的一个测试例子:

__attribute__((constructor))
__attribute__((destructor))

  1.   
  2.   
  3. #include<stdio.h>  
  4. __attribute__((constructor)) void before_main()  
  5. {  
  6.    printf("before main\n");  
  7. }  
  8.   
  9. __attribute__((destructor)) void after_main()  
  10. {  
  11.    printf("after main\n");  
  12. }  
  13.   
  14. int main()  
  15. {  
  16.    printf("in main\n");  
  17.    return 0;  
  18. }  

$ gcc test.c -o test
$ ./test
before main
in main
after main

根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.

说到C++里面的全局类对象的构造,我们不禁要问全局类对象的构造跟__attribute__((constructor))以及destructor谁在前谁在后呢?

 

  1. #include<iostream>  
  2. using namespace std;  
  3. __attribute__((constructor)) void before_main()  
  4. {  
  5.     cout<<"Before Main"<<endl;  
  6. }  
  7. __attribute__((destructor)) void after_main()  
  8. {  
  9.     cout<<"After Main"<<endl;  
  10. }  
  11. class AAA{  
  12.     public:  
  13.     AAA(){  
  14.         cout<<"AAA construct"<<endl;  
  15.     }     
  16.     ~AAA(){  
  17.         cout<<"AAA destructor" <<endl;  
  18.     }     
  19. };  
  20. AAA A;  
  21. int main()  
  22. {  
  23.     cout<<"in main"<<endl;  
  24.     return 0;  
  25. }  

$ make test2

$ ./test2

AAA construct
Before Main
in main
AAA destructor
After Main

可以看到全局类的构造过程发生在before_main()函数前面,而析构也发生在after_main()前面.

转载于:https://my.oschina.net/u/263896/blog/56603

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值