vendredi 25 septembre 2015

c++ Using this pointer in constructors with std::list

I found this code somewhere, and I have found several people asking questions about why their implementation wasn't working, and every single fix is essentially the same code I've written myself, but there is a runtime error and I am not sure why. I am using VS2013, and haven't checked if any other IDEs work.

The error is:

    Unhandled exception at 0x010D9B46 in ConceptTest.exe: 
    0xC0000005: Access violation reading location 0x00000000.

Here is some code:

    class GameObject
    {
    public:
       GameObject();
       ~GameObject();

       static std::list<GameObject*> dead;
       static std::list<GameObject*> active;

   protected:
       std::list<GameObject*>::iterator it;
    };

    std::list<GameObject*> GameObject::active;
    std::list<GameObject*> GameObject::dead;

    GameObject::GameObject()
    {
       active.push_front(this);
    }

The error doesn't occur if I create a function and add the "this" pointer to the list within that function, it only happens within the constructor and my question is: why?

for example this works:

    void GameObject::Create()
    {
          active.push_front(this);
    }

P.S. I think this pattern has a name (at least it seems similar to the Singleton pattern) and I would like to know if anybody knows it.

Aucun commentaire:

Enregistrer un commentaire