Reputation: 3030
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
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:
If you're okay with the above, go ahead and pull the trigger!
Upvotes: 3