博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

os fans

MSN & Mail:jinglexy at yahoo dot com dot cn
操作系统开发博客圈:http://blog.chinaunix.net/group/group_507.html
qq group(os fans): 3*2*2*6*2*9*2
  jinglexy.cublog.cn

关于作者
马甲:天衣有缝
职业:linux driver
位置:徐家汇上海交大
|| << >> ||
我的分类


执行c++构造函数(原创)
对于全局对象,特殊情况下构造函数不会执行。如c++写的os。

链接器把构造函数放在start_ctors和end_ctors之间,所以我们可以这样做:
    for (i = &start_ctors; i < &end_ctors; i++) {
        foo = (CONSTRUCTOR_FUNC)*i;
        foo();        /* 构造函数不能用 cout对象,这个时候控制台还没有初始化 */
    }

引出一个特殊需求,全局对象按顺序构造,我们显然无法预知start_ctors表顺序。
一个可行的方法使用重载new,并用模板函数封装其执行:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct test_t
{
public:
    test_t()
    {
        printf("construct of test_t()\n");
    }

    int a;
    int b;

};


void * operator new (size_t size, void * place)
{
    return place;
}

/* call the default constructor */
template <class object_t> void construct(object_t * ptr)
{
    new (ptr) object_t();
}


test_t t;
int main(int argc, char* argv[])
{
    construct(&t);

    return 0;
}


发表于: 2008-05-24,修改于: 2008-05-25 13:08,已浏览272次,有评论0条 推荐 投诉


网友评论
 发表评论