Reputation: 43497
Why is this not a more popular idiom/pattern?
#include <list>
class A {
int data;
static std::list<A*> glist;
public:
A():data(0) {
glist.push_back(this);
}
~A() {
glist.remove(this);
}
};
It's like a safety net. You can delete an instance of A
from any pointer to it and the list manages itself. Isn't this so much better than creating separate containers to keep track of your A
's and making mistakes managing them? I guess I'm making a big deal out of something really basic. But I bet this could have saved me lots of debug time in the past.
Upvotes: 0
Views: 811
Reputation: 96291
It's not thread safe. Sometimes you're already maintaining the object list and don't care. Objects on the stack don't really need to be tracked in another container. It introduces a new dependency of your class that may not be needed. I'm sure there are many more reasons I missed.
The object management issues aren't issues if you use shared_ptr
or boost's ptr containers.
Upvotes: 0
Reputation: 174
The problem would be the static keyword. You can have only one global list - no separate lists, since the static keyword would ensure that all instances of your A class will belong to one and only list; you will not be able to create separate lists of A's. If that is indeed your intention, then this should be fine. However, I would also add that there is unnecessary redundancy here - std::list internally manages these things for you - I don't understand why you would want to add an extra layer of abstraction over it.
Upvotes: 2