简体   繁体   中英

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM