Posted on 2008-05-14 18:00
天衣有縫 閱讀(908)
評論(0) 編輯 收藏 引用
對于全局對象,特殊情況下構造函數不會執行。如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;
}