开发者

C++: implicit linked list

开发者 https://www.devze.com 2023-02-19 07:50 出处:网络
Why is this not a more popular开发者_开发问答 idiom/pattern? #include <list> class A { int data;

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消