__attribute__ ((constructor));

本文介绍GCC提供的构造函数和析构函数属性,通过示例展示了如何在C++程序中利用这些属性来实现特定的功能,如在main()函数前后执行特定任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gcc为函数提供了几种类型的属性,其中包含:构造函数(constructors)和析构函数(destructors)。

程序员应当使用类似下面的方式来指定这些属性:

   static void start(void) __attribute__((constructor));
    static void stop(void)__attribute__ ((destructor));
带有"构造函数"属性的函数将在main()函数之前被执行,而声明为"析构函数"属性的函数则将在main()退出时执行。

用法举例:

#include <iostream>

void breforemain() __attribute__((constructor));
void aftermain() __attribute__((destructor));
class AAA{
public:
      AAA(){std::cout<< "before main function AAA"<< std::endl;}
      ~AAA(){std::cout<< "after main function AAA"<< std::endl;}
};
AAA aaa;
void breforemain()
{
    std::cout<< "before main function"<< std::endl;
}

void aftermain()
{
    std::cout<< "after main function"<< std::endl;
}

int main(int argc,char** argv)
{
    std::cout<< "in main function"<< std::endl;
    return0;
}

输出结果:

beforemain function AAA
before main function
in main function
after main function AAA
after main function

__attribute__((constructor))标志的代码将在main函数前调用,就像在C++里面的全局变量类的构造一样。
此时难免有疑问,全局类对象的构造跟__attribute__((constructor))以及destructor到底是什么执行顺序?
实验表示,全局类的构造过程发生在before_main()函数之前,而析构也发生在after_main()前面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值