I am working on a library where users should be able to use static global instances. These instances (being run before main) register themselves in another global vector which can then be used…
Currently, it goes somewhat like this…
class A;
std::vector<A*> v;
class A {
public:
A (int i) : i(i) {
v.push_back(this);
}
int get () const {
return this->i;
}
private:
int i;
};
A a(1);
A b(2);
int main ()
{
for (A* const& c : v)
std::cout << c->get() << std::endl;
for (std::vector<A*>::iterator i = v.begin(); i != v.end(); i++)
delete *i;
return 0;
}
However, I’m afraid this code will leak… even more so when I don’t want users to explicitely delete the contents of the vector (they’ll forget it anyway), it should happen automatically at the end of main.
Are there other solutions? I wanted to use a vector of std::unique_ptr, but apparently they don’t work that way…
std::vector, and it cleans itself up on destruction.aandbare correctly destroyed and released at the end of execution.deletethings that weren’t allocated withnew.Also, you are relying on
vbeing initialised beforeaandbare constructed. You should lazily initialisevinstead (see below).To get what you want, just remove the loop that deletes those objects.
Here’s your code running in action with the loops removed and some debug output added. Notice that both objects are destroyed correctly.