George
George

Reputation: 3030

C++: Deleting an Object in a static vector of pointers with the destructor?

Here's how my class is set up:

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

    static vector<Foo*> foos;
}

Foo::Foo(){
    foos.push_back(this);
}
Foo::~Foo(){}

Let's say I create an Object Foo like this:

int main(){
    Foo *obj = new Foo();
}

How would I go about deleting this object, as well as the pointer in the static vector?

Upvotes: 2

Views: 972

Answers (1)

InsertMemeNameHere
InsertMemeNameHere

Reputation: 2433

Change the implementation of Foo::~Foo to

Foo::~Foo()
{
    foos.erase(std::find(foos.begin(), foos.end(), this));
}

...use std::unique_ptr...

int main(int argc, char **argv)
{
    std::unique_ptr<Foo> ptr{new Foo{}};

    return 0;
}

... and it will clean up after itself.

Problems include:

  • Not thread safe.
  • A worst case time of O(n) per deletion for n instances.
  • Evil global state!

If you're okay with the above, go ahead and pull the trigger!

Upvotes: 3

Related Questions