全局對象在程序進入main之前construct, 離開main後destruct

Solve  Bjarne Stroustrup's little puzzle:

Given the program:

#include <iostream.h> // DON'T use <iostream> or using namespace std;


main() {
    cout << "Hello world" << endl;
}

modify it to produce the output:
Initialize
Hello world
Clean up

ps: Do not change the function main() in any way. and only modify this cpp file.

Answer: 利用全局對象在程序進入main之前construct, 離開main後destruct之特點

#include <iostream.h> // DON'T use <iostream> or using namespace std;
class A {
public:
    A() { cout<< "Initialize: " << endl; }
    ~A() { cout<< "Clean up " << endl;}
};
A test;   //建立一個全局對象,調用 A::A()
main() {
    cout << "Hello world" << endl;
}

// 析構: 調用A::~()

對於C程序通過設置函數屬性爲constuctor, 可使其在main()之前運行:

#include <stdio.h>
void first() __attribute__((constructor));
void first()
{
        printf("this is function %s/n", __FUNCTION__);
        return;
}
int main(int argc, char **argv)
{
        printf("this is function %s/n", __FUNCTION__);
        return 0;
}

運行結果:

this is function first
this is function main
this is function main
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章