arb 的静态 ctor/dtor 观察者。 C++类

发布于 2024-10-01 03:36:42 字数 4322 浏览 3 评论 0原文

我有一系列的类 AB ...,它们有许多派生类,这些派生类是在我不想更改的模块内创建的。

此外,我至少有一个类 Z,每当 A 类型的对象(或派生类)被创建被摧毁。将来可能会有更多的类,YX想要观察不同的对象。

我正在寻找一种方便的方法来解决这个问题。 乍一看,这个问题似乎微不足道,但我现在有点陷入困境。

我想出了两个基类 SpawnObserverSpawnObservable ,它们应该可以完成这项工作,但由于几个原因我对它们非常不满意(请参阅随附的简化这些课程)。

  1. 当通知 Z 时,由于基类的顺序,实际对象要么尚未存在,要么不再存在创建/销毁。尽管在销毁对象时可以比较指针(以将它们从 Z 中的某些数据结构中删除),但这在创建对象时不起作用,并且当您具有多重继承时肯定不起作用。< /strong>
  2. 如果您只想观察一个类,例如 A,您总是会收到所有 (A, B, ... )。
  3. 您必须在所有类中显式执行 if/else,因此您必须知道所有从 SpawnObservable 继承的类,这是非常糟糕的。

以下是我试图将其精简为最基本的功能的类,您需要了解这些功能才能理解我的问题。简而言之:您只需从 SpawnObservable 继承,ctor/dtor 就会完成通知观察者的工作(好吧,至少,这是我想要)。

#include <list>
#include <iostream>

class SpawnObservable;

class SpawnObserver {
  public:
    virtual void ctord(SpawnObservable*) = 0;
    virtual void dtord(SpawnObservable*) = 0;
};

class SpawnObservable {
  public:
    static std::list<SpawnObserver*> obs;
    SpawnObservable() {
      for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
        (*it)->ctord(this);
      }
    }
    ~SpawnObservable() {
      for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
        (*it)->dtord(this);
      }
    }
    virtual void foo() {} // XXX: very nasty dummy virtual function
};
std::list<SpawnObserver*> SpawnObservable::obs;

struct Dummy {
  int i;
  Dummy() : i(13) {}
};

class A : public SpawnObservable {
  public:
    Dummy d;
    A() : SpawnObservable() {
      d.i = 23;
    }
    A(int i) : SpawnObservable() {
      d.i = i;
    }
};

class B : public SpawnObservable {
  public:
    B() { std::cout << "making B" << std::endl;}
    ~B() { std::cout << "killing B" << std::endl;}
};

class PrintSO : public SpawnObserver { // <-- Z
  void print(std::string prefix, SpawnObservable* so) {
    if (dynamic_cast<A*>(so)) {
      std::cout << prefix << so << " " << "A: " << (dynamic_cast<A*>(so))->d.i << std::endl;
    } else if (dynamic_cast<B*>(so)) {
      std::cout << prefix << so << " " << "B: " << std::endl;
    } else {
      std::cout << prefix << so << " " << "unknown" << std::endl;
    }
  }
  virtual void ctord(SpawnObservable* so) {
    print(std::string("[ctord] "),so);
  }
  virtual void dtord(SpawnObservable* so) {
    print(std::string("[dtord] "),so);
  }
};


int main(int argc, char** argv) {
  PrintSO pso;
  A::obs.push_back(&pso);
  B* pb;
  {
    std::cout << "entering scope 1" << std::endl;
    A a(33);
    A a2(34);
    B b;
    std::cout << "adresses: " << &a << ", " << &a2 << ", " << &b << std::endl;
    std::cout << "leaving scope 1" << std::endl;
  }
  {
    std::cout << "entering scope 1" << std::endl;
    A a;
    A a2(35);
    std::cout << "adresses: " << &a << ", " << &a2 << std::endl;
    std::cout << "leaving scope 1" << std::endl;
  }
  return 1;
}

输出是:

entering scope 1
[ctord] 0x7fff1113c640 unknown
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c660 unknown
making B
adresses: 0x7fff1113c640, 0x7fff1113c650, 0x7fff1113c660
leaving scope 1
killing B
[dtord] 0x7fff1113c660 unknown
[dtord] 0x7fff1113c650 unknown
[dtord] 0x7fff1113c640 unknown
entering scope 1
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c640 unknown
adresses: 0x7fff1113c650, 0x7fff1113c640
leaving scope 1
[dtord] 0x7fff1113c640 unknown
[dtord] 0x7fff1113c650 unknown

我想强调,我完全清楚为什么我的解决方案的行为方式如此。我的问题是你是否有更好的方法来做到这一点。

编辑

作为这个问题的扩展(并受到下面评论的启发),我想知道: 为什么你认为这是一个糟糕的方法?

作为附加说明:我试图通过此完成的是在每个创建的对象中安装一个普通的观察者。

编辑2

我会接受解决问题1的答案(上面列举的粗体字)描述了为什么整个事情是一个非常糟糕的主意。

I have a series of classes A, B, ... which have many derived classes which are created inside a module I do not wish to change.

Additionally, I have at least one class Z, which has to be informed whenever an object of type A (or derived classes) is created or destroyed. In the future, there may be more classes, Y, X that want to observe different objects.

I am looking for a convenient way to solve this.
At first glance, the problem seemed trivial, but I'm kind of stuck right now.

What I came up with, is two base classes SpawnObserver and SpawnObservable which are supposed to do the job, but I am very unhappy with them for several reasons (see attached simplification of these classes).

  1. When Z is notified, the actual object is either not yet or not anymore existent, due to the order in which base classes are created/destroyed. Although the pointers can be compared when destroying an object (to remove them from some data-structures in Z) this does not work when it is created and it surely does not work when you have multiple inheritance.
  2. If you want to observe only one class, say A, you are always notified of all (A, B, ...).
  3. You have to explicitly if/else through all classes, so you have to know all classes that inherit from SpawnObservable, which is pretty bad.

Here are the classes, which I tried to trim down to the most basic functionality, which you need to know to understand my problem. In a nutshell: You simply inherit from SpawnObservable and the ctor/dtor does the job of notifying the observers (well, at least, this is what I want to have).

#include <list>
#include <iostream>

class SpawnObservable;

class SpawnObserver {
  public:
    virtual void ctord(SpawnObservable*) = 0;
    virtual void dtord(SpawnObservable*) = 0;
};

class SpawnObservable {
  public:
    static std::list<SpawnObserver*> obs;
    SpawnObservable() {
      for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
        (*it)->ctord(this);
      }
    }
    ~SpawnObservable() {
      for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
        (*it)->dtord(this);
      }
    }
    virtual void foo() {} // XXX: very nasty dummy virtual function
};
std::list<SpawnObserver*> SpawnObservable::obs;

struct Dummy {
  int i;
  Dummy() : i(13) {}
};

class A : public SpawnObservable {
  public:
    Dummy d;
    A() : SpawnObservable() {
      d.i = 23;
    }
    A(int i) : SpawnObservable() {
      d.i = i;
    }
};

class B : public SpawnObservable {
  public:
    B() { std::cout << "making B" << std::endl;}
    ~B() { std::cout << "killing B" << std::endl;}
};

class PrintSO : public SpawnObserver { // <-- Z
  void print(std::string prefix, SpawnObservable* so) {
    if (dynamic_cast<A*>(so)) {
      std::cout << prefix << so << " " << "A: " << (dynamic_cast<A*>(so))->d.i << std::endl;
    } else if (dynamic_cast<B*>(so)) {
      std::cout << prefix << so << " " << "B: " << std::endl;
    } else {
      std::cout << prefix << so << " " << "unknown" << std::endl;
    }
  }
  virtual void ctord(SpawnObservable* so) {
    print(std::string("[ctord] "),so);
  }
  virtual void dtord(SpawnObservable* so) {
    print(std::string("[dtord] "),so);
  }
};


int main(int argc, char** argv) {
  PrintSO pso;
  A::obs.push_back(&pso);
  B* pb;
  {
    std::cout << "entering scope 1" << std::endl;
    A a(33);
    A a2(34);
    B b;
    std::cout << "adresses: " << &a << ", " << &a2 << ", " << &b << std::endl;
    std::cout << "leaving scope 1" << std::endl;
  }
  {
    std::cout << "entering scope 1" << std::endl;
    A a;
    A a2(35);
    std::cout << "adresses: " << &a << ", " << &a2 << std::endl;
    std::cout << "leaving scope 1" << std::endl;
  }
  return 1;
}

The output is:

entering scope 1
[ctord] 0x7fff1113c640 unknown
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c660 unknown
making B
adresses: 0x7fff1113c640, 0x7fff1113c650, 0x7fff1113c660
leaving scope 1
killing B
[dtord] 0x7fff1113c660 unknown
[dtord] 0x7fff1113c650 unknown
[dtord] 0x7fff1113c640 unknown
entering scope 1
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c640 unknown
adresses: 0x7fff1113c650, 0x7fff1113c640
leaving scope 1
[dtord] 0x7fff1113c640 unknown
[dtord] 0x7fff1113c650 unknown

I want to stress, that I am perfectly aware why my solution behaves the way it does. My question is whether you have a better approach of doing this.

EDIT

As an extension to this question (and inspired by the comments below), I'd like to know:
Why do you think this is a terrible approach?

As an additional note: What I an trying to accomplish by this is to install a normal Observer in each and every created object.

EDIT 2

I will accept an answer that solves problem 1 (bold one in the enumeration above) or describes why the whole thing is a very bad idea.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

等风来 2024-10-08 03:36:42

使用奇怪的重复模板模式。

template<typename T> class watcher {
    typename std::list<T>::iterator it;
    watcher();
    ~watcher();
    void ctord(T*);
    void dtord(T*);    
};
template<typename T> class Observer {
public:

    typedef std::list<T*> ptr_list;
    static ptr_list ptrlist;
    typedef typename ptr_list::iterator it_type;
    it_type it;

    typedef std::list<watcher<T>*> watcher_list;
    static watcher_list watcherlist;
    typedef typename watcher_list::iterator watcher_it_type;

    Observer() {
       ptrlist.push_back(this);
       it_type end = ptrlist.end();
       end--;
       it = end;
       for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
           w_it->ctord(this);
    }
    ~Observer() {
        ptrlist.erase(it);
       for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
           w_it->ctord(this);
    }
};
class A : public Observer<A> {
};
class B : public Observer<B> {
};
class C : public A, public B, public Observer<C> {
    // No virtual inheritance required - all the Observers are a different type.
};
template<typename T> watcher<T>::watcher<T>() {
    Observer<T>::watcherlist.push_back(this);
    it = watcherlist.end();
    it--;         
}
template<typename T> watcher<T>::~watcher<T>() {
    Observer<T>::watcherlist.erase(it);
}
template<typename T> void watcher<T>::ctord(T* ptr) {
    // ptr points to an instance of T that just got constructed
}
template<typename T> void watcher<T>::dtord(T* ptr) {
    // ptr points to an instance of T that is just about to get destructed.
}

不仅如此,您还可以使用此技术多次继承 Observer,因为两个 ObserverObserver 是不同的类型,因此不需要钻石继承或类似的东西。另外,如果您需要 ObserverObserver 的不同功能,您可以进行专门化。

编辑@注释:

类 C 确实分别通过 A 和 B 继承自 ObserverObserver。它不需要知道或关心它们是否被观察。 AC 实例最终将出现在所有三个列表中。

至于ctord和dtord,我实际上并没有看到它们执行什么功能。您可以使用 Observer::ptrlist 获取任何特定类型的列表。

再次编辑:哦哦,我明白了。请稍等一下,我正在编辑一些内容。伙计,这是我写过的最可怕的代码之一。您应该认真考虑不需要它。为什么不只让需要了解其他对象的对象来进行创建呢?

Use the curiously recurring template pattern.

template<typename T> class watcher {
    typename std::list<T>::iterator it;
    watcher();
    ~watcher();
    void ctord(T*);
    void dtord(T*);    
};
template<typename T> class Observer {
public:

    typedef std::list<T*> ptr_list;
    static ptr_list ptrlist;
    typedef typename ptr_list::iterator it_type;
    it_type it;

    typedef std::list<watcher<T>*> watcher_list;
    static watcher_list watcherlist;
    typedef typename watcher_list::iterator watcher_it_type;

    Observer() {
       ptrlist.push_back(this);
       it_type end = ptrlist.end();
       end--;
       it = end;
       for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
           w_it->ctord(this);
    }
    ~Observer() {
        ptrlist.erase(it);
       for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
           w_it->ctord(this);
    }
};
class A : public Observer<A> {
};
class B : public Observer<B> {
};
class C : public A, public B, public Observer<C> {
    // No virtual inheritance required - all the Observers are a different type.
};
template<typename T> watcher<T>::watcher<T>() {
    Observer<T>::watcherlist.push_back(this);
    it = watcherlist.end();
    it--;         
}
template<typename T> watcher<T>::~watcher<T>() {
    Observer<T>::watcherlist.erase(it);
}
template<typename T> void watcher<T>::ctord(T* ptr) {
    // ptr points to an instance of T that just got constructed
}
template<typename T> void watcher<T>::dtord(T* ptr) {
    // ptr points to an instance of T that is just about to get destructed.
}

Not just that, but you can inherit from Observer multiple times using this technique, as two Observer<X> and Observer<Y> are different types and thus doesn't require diamond inheritance or anything like that. Plus, if you need different functionality for Observer<X> and Observer<Y>, you can specialize.

Edit @ Comments:

class C DOES inherit from Observer<A> and Observer<B> through A and B, respectively. It doesn't need to know or care whether or not they're being observed. A C instance will end up on all three lists.

As for ctord and dtord, I don't actually see what function they perform. You can obtain a list of any specific type using Observer::ptrlist.

Edit again: Oooooh, I see. Excuse me a moment while I edit some more. Man, this is some of the most hideous code I've ever written. You should seriously consider not needing it. Why not just have the objects that need to be informed about the others do their creation?

木格 2024-10-08 03:36:42

问题1并不容易解决(事实上我认为这是不可能解决的)。奇怪的重复出现的模板想法最接近解决这个问题,因为基类对派生类型进行编码,但是如果您确实坚持在构造基类时了解派生类型,则必须向每个派生类添加基类。

如果您不介意执行实际操作(我的意思是簿记除外)或检查每个对象的构造函数或析构函数之外的列表,那么您可以仅在操作即将进行时才(重新)构建最小列表被执行。这使您有机会使用完整构造的对象,并且更容易解决问题 2。

为此,您可以首先拥有已构造但不在“完整”列表中的对象列表。 “完整”列表将包含每个构造对象的两个指针。一种是指向基类的指针,您将从 Observable 构造函数中存储该指针,在构造单个对象期间可能会多次存储该指针。另一个是 void *,指向对象的最派生部分 - 使用 dynamic_cast 来检索它 - 并用于确保每个对象仅在列表中出现一次。

当一个对象被销毁时,如果它有多个 Observable 基数,每个基数都会尝试从列表中删除自己,而当涉及到完整列表时,只有一个会成功 - 但这没关系,因为每个都可以作为该对象的任意基础。

下面是一些代码。

您的完整对象列表,可以以 std::map 允许的简单方式进行迭代。 (每个void *和每个Observable *都是唯一的,但这使用Observable *作为键,这样很容易删除条目在 Observable 析构函数中。)

typedef std::map<Observable *, void *> AllObjects;
AllObjects allObjects;

以及已构造但尚未添加到 allObjects 的对象列表:

std::set<Observable *> recentlyConstructedObjects;

Observable 构造函数中,将新对象添加到待处理对象列表中:

recentlyConstructedObjects.insert(this);

Observable 析构函数中,删除该对象:

// 'this' may not be a valid key, if the object is in 'allObjects'.
recentlyConstructedObjects.erase(this);

// 'this' may not be a valid key, if the object is in 'recentlyConstructedObjects',
// or this object has another Observable base object and that one got used instead.
allObjects.erase(this);

在开始执行操作之前,更新 allObjects(如果存在)自上次更新以来已经构建了任何对象:

if(!recentlyConstructedObjects.empty()) {
    std::map<void *, Observable *> newObjects;
    for(std::set<Observable *>::const_iterator it = recentlyConstructedObjects.begin(); it != recentlyConstructedObjects.end(); ++it)
        allObjectsRev[dynamic_cast<void *>(*it)] = *it;

    for(std::map<void *, Observable *>::const_iterator it = newObjects.begin(); it != newObjects.end(); ++it)
        allObjects[it->second] = it->first;

    recentlyConstructedObjects.clear();
}

现在您可以访问每个对象一次:

for(std::map<Observable *,void *>::const_iterator it = allObjects.begin(); it != allObjects.end(); ++it) {
    // you can dynamic_cast<whatever *>(it->first) to see what type of thing it is
    //
    // it->second is good as a key, uniquely identifying the object
}

好吧......既然我已经写了所有这些,我不确定这是否可以解决您的问题。尽管如此,考虑一下还是很有趣的。

(这个想法将解决奇怪的重复模板的问题之一,即每个派生对象都有很多基对象,因此很难解开。(不幸的是,抱歉,没有解决大量基类的问题。 )由于使用了dynamic_cast,当然,如果你在对象的构造过程中调用它,它并没有多大用处,这当然是奇怪的重复性事情的优点:你在构造过程中知道派生类型 (所以,如果您采用这种解决方案,

并且您可以在构造/销毁阶段之外执行操作,并且您不介意(多个)基类占用空间,那么您可以也许让每个基的构造函数存储一些特定于类的信息 - 可能使用 typeid 或特征 - 并在构建更大的列表时将它们合并在一起 这应该很简单,因为您会知道。哪些基础对象对应于相同的派生对象。根据您想要执行的操作,这可能会帮助您解决问题 3。)

Issue 1 isn't easily solved (in fact I think it's impossible to fix). The curiously recurring template idea comes closest to solving it, because the base class encodes the derived type, but you'll have to add a base to every derived class, if you really insist on knowing the derived type when the base is being constructed.

If you don't mind performing your actual operations (other than the bookkeeping, I mean) or examining the list outside the constructor or destructor of each object, you could have it (re)build the minimal list only when the operation is about to be performed. This gives you a chance to use the fully-constructed object, and makes it easier to solve issue 2.

You'd do this by first having a list of objects that have been constructed, but aren't on the 'full' list. And the 'full' list would contain two pointers per constructed object. One is the pointer to the base class, which you'll store from the Observable constructor, possibly multiple times during the construction of a single object. The other is a void *, pointing to the most derived part of the object -- use dynamic_cast<void *> to retrieve this -- and is used to make sure that each object only appears once in the list.

When an object is destroyed, if it has multiple Observable bases, each will try to remove itself from the lists, and when it comes to the full list, only one will succeed -- but that's fine, because each is equally good as an arbitrary base of that object.

Some code follows.

Your full list of objects, iterable in as straightforward a fashion as std::map will allow. (Each void * and each Observable * is unique, but this uses the Observable * as the key, so that it's easy to remove the entry in the Observable destructor.)

typedef std::map<Observable *, void *> AllObjects;
AllObjects allObjects;

And your list of objects that have been constructed, but aren't yet added to allObjects:

std::set<Observable *> recentlyConstructedObjects;

In the Observable constructor, add the new object to the list of pending objects:

recentlyConstructedObjects.insert(this);

In the Observable destructor, remove the object:

// 'this' may not be a valid key, if the object is in 'allObjects'.
recentlyConstructedObjects.erase(this);

// 'this' may not be a valid key, if the object is in 'recentlyConstructedObjects',
// or this object has another Observable base object and that one got used instead.
allObjects.erase(this);

Before you're about to do your thing, update allObjects, if there've been any objects constructed since last time it was updated:

if(!recentlyConstructedObjects.empty()) {
    std::map<void *, Observable *> newObjects;
    for(std::set<Observable *>::const_iterator it = recentlyConstructedObjects.begin(); it != recentlyConstructedObjects.end(); ++it)
        allObjectsRev[dynamic_cast<void *>(*it)] = *it;

    for(std::map<void *, Observable *>::const_iterator it = newObjects.begin(); it != newObjects.end(); ++it)
        allObjects[it->second] = it->first;

    recentlyConstructedObjects.clear();
}

And now you can visit each object the once:

for(std::map<Observable *,void *>::const_iterator it = allObjects.begin(); it != allObjects.end(); ++it) {
    // you can dynamic_cast<whatever *>(it->first) to see what type of thing it is
    //
    // it->second is good as a key, uniquely identifying the object
}

Well... now that I've written all that, I'm not sure whether this solves your problem. It was interesting to consider nonetheless.

(This idea would solve one of the problems with the curiously recurring template, namely that you have lots of base objects per derived object and it's harder to disentangle because of that. (Unfortunately, no solution to the large number of base classes, sorry.) Due to the use of dynamic_cast, of course, it's not much use if you call it during an object's construction, which is of course the advantage of the curiously recurring thing: you know the derived type during the base's construction.

(So, if your'e going with that style of solution, AND you are OK with performing your operations outside the construction/destruction stage, AND you don't mind the (multiple) base classes taking up space, you could perhaps have each base's constructor store some class-specific info -- using typeid, perhaps, or traits -- and merge these together when you build the larger list. This should be straightforward, since you'll know which base objects correspond to the same derived object. Depending on what you're trying to do, this might help you with issue 3.)

臻嫒无言 2024-10-08 03:36:42

查看信号和插槽,尤其是Boost 信号和插槽

Take a look at Signals and Slots especially Boost Signals and Slots

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文