对象计数器

时间:2019-03-14 16:30:48

标签: c++ templates design-patterns

我想针对曾经实例化的每个类类型进行计数。首先,有人以这种方法为例:

class Person
{
public:
    Person() {
        objects.push_back(this);
    }
    virtual ~Person() {
        objects.erase(this);
    }

static void print_types()
{
    for (auto pers : container)
    {
        std::cout << typeid(*pers).name() << "\n";
    }
}
private:
    static std::set<const Person*> objects;
};

class Employee : public Person
{
};


class Employee2 : public Employee
{
};

每次对其中一个类进行实例化时,我都会跟踪对象,并且可以使用print_types()知道到目前为止我已经创建了多少种类型。请注意,Employee2是从Employee继承的,而不是从Person继承的(我需要它来实现链继承)

我想扩展它,以便每个类型有两个计数器:created和alive。问题是您不能轻易地从基类Person的构造函数/析构函数中获取计数器,因为当从构造函数/析构函数调用时,typeid(* this)将返回基类类型。

另一个建议是使用CRTP模式,但是当您使用链式继承时,这种方法不起作用。

还有另一种实现此类计数器的方法吗?

1 个答案:

答案 0 :(得分:0)

我只是玩了一下。也许这对您有帮助。它总是打印正确的类(而不是基类)的值。

但是实际上是一样的^^。

标题:

#include <set>
#include <string>

class observeable;
class observer
{
public:
  observer() = delete;
  static void print();
  static std::set< observeable* > items;
};

class observeable
{
public:
  observeable();
  virtual ~observeable();
  virtual std::string get_typeid();
};

来源:

std::set< observeable* > observer::items;

void observer::print()
{
  std::cout << "Called" << std::endl;
  for( auto item : items )
    std::cout << item->get_typeid() << std::endl;
}

observeable::observeable()
{
  observer::items.insert( this );
}

observeable::~observeable()
{
  observer::items.erase( this );
}

std::string observeable::get_typeid()
{
  return std::string( typeid(*this).name() );
}

主要:

#include <memory>

class A : observeable
{};

class B : A
{};

class C : observeable 
{};

int main()
{
  A a;
  B b;
  observer::print(); // A B present

  {
    C d;
  }
  observer::print(); // no C present

  auto d_heap = std::shared_ptr<C>( new C() );
  observer::print(); // C present
  return 0;
}