lundi 30 janvier 2017

Strange behaviour in atexit()

Let's suppose we have the following (bad) code which does stuff at exit:

//Singleton class Test
class Test{
public:

    static Test& getTest(){
        static Test t;
        return t;
    }

    void addElement(std::string s){
        list[index] = s;
        index++;
    }

    void print(){
        for(int i = 0; i < index; i++){
            cout << list[i] << endl;
        }
    }

private:
    int index = 0;
    std::array<std::string, 30> list;

};

//Function called at exit
void onExit(){
    Test::getTest().addElement("Another one");
    Test::getTest().print();
}

//...and main

int main()
{
    std::atexit(onExit);
    Test::getTest().addElement("String");
    return 0;
}

The first time I saw this I expected the following output:

String
Another one

But strangely it prints

Another one
Another one

Is there something I am missing? Does the array get cleared and filled...twice?

Aucun commentaire:

Enregistrer un commentaire