문제

I need you guys help in (may be basic question, sorry for that) in CRTP. This is based on following posts: C++ object lifetime profiling How to count the number of CRTP subclasses of a template class?

Using CRTP, we can able to count the number of objects created for each class type. But, using this approach I can't find the total number of objects created in the system.

Is there any way to achieve this?

Thanks in advance.

Regards, SNR

도움이 되었습니까?

해결책

This solution contains code for both (per-class and global) counters.

extern size_t Global_counter; //In .cpp file define it: size_t Global_counter = 0;

template <class T>
class CountedClass
{
protected:
  static size_t this_class_counter;

public:
  static size_t GetThisClassCounter()
  {
    return this_class_counter;
  }

  static size_t GetGlobalCounter()
  {
    return Global_counter;
  }

  CountedClass()
  {
    ++this_class_counter;
    ++Global_counter;
  }
};

template <class T>
size_t CountedClass<T>::this_class_counter = 0;

Sample usage:

class A : public CountedClass<A>
{
public:
  A() : CountedClass<A>()
  {
  }
};

class B : public CountedClass<B>
{
public:
  B() : CountedClass<B>()
  {
  }
};

A a1;
A a2;
B b2;

std::cout<<A::GetThisClassCounter(); //prints 2
std::cout<<A::GetGlobalCounter(); //prints 3

std::cout<<B::GetThisClassCounter(); //prints 1
std::cout<<B::GetGlobalCounter(); //prints 3

다른 팁

Have all classes inherit from a common base class which keeps a counter, something like

class Counter {
  static int count = 0;

protected:
  Counter() { count++; }

public:
  int getCount() { return count; }
};

As you want to count all the instances you don't need to distinguish different derived classes, so you don't need CRTP.

If you want both counts you can use a class like the one above as a base class for your CRTP class.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top