Chinaunix首页 | 论坛 | 博客
  • 博客访问: 704151
  • 博文数量: 60
  • 博客积分: 2849
  • 博客等级: 少校
  • 技术积分: 1011
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-10 15:38
文章分类
文章存档

2013年(4)

2012年(11)

2011年(5)

2010年(3)

2009年(9)

2008年(19)

2007年(9)

分类: C/C++

2008-05-24 21:54:12

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

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

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

#include
#include
#include
#include

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 void construct(object_t * ptr)
{
    new (ptr) object_t();
}


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

    return 0;
}


阅读(1822) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~