如果你不能拿不出工具,你就能够使用混合代码,在你喜欢的课堂上添加记号(你可能希望将产出到日志档案中)。 如果你提出问题,我现在就没有时间了,我稍后会回头。
#include <utility>
#include <iostream>
#include <atomic>
#include <string_view>
class report_instance_count_itf
{
public:
virtual void report_construction(std::string_view type_name, std::size_t number_of_instances) const noexcept = 0;
virtual void report_destruction(std::string_view type_name, std::size_t number_of_instances) const noexcept = 0;
};
class cout_reporter_t : public report_instance_count_itf
{
public:
void report_construction(std::string_view type_name, std::size_t number_of_instances) const noexcept override
{
std::cout << "construct of class `" << type_name << "` number of instances = " << number_of_instances << "
";
}
void report_destruction(std::string_view type_name, std::size_t number_of_instances) const noexcept override
{
std::cout << "destruction of class `" << type_name << "` number of instances = " << number_of_instances << "
";
}
};
//------------------------------------------------------------------------------
// meyers singleton for now (ideally inject)
const report_instance_count_itf& get_instance_count_reporter()
{
static cout_reporter_t reporter;
return reporter;
}
//------------------------------------------------------------------------------
// Reusable instance counter implementation,
// make it a class template so we get a unique "instance" per
// class type that uses it.
// put this class template in its own header file
template<typename class_t>
class instance_counter_impl_t
{
public:
instance_counter_impl_t()
{
++m_instance_count;
const std::type_info& ti = typeid(class_t);
get_instance_count_reporter().report_construction(ti.name(), m_instance_count);
}
~instance_counter_impl_t()
{
--m_instance_count;
const std::type_info& ti = typeid(class_t);
get_instance_count_reporter().report_destruction(ti.name(), m_instance_count);
}
const auto instance_count() const noexcept
{
return m_instance_count;
}
private:
static std::atomic<std::size_t> m_instance_count;
};
template<typename class_t>
std::atomic<std::size_t> instance_counter_impl_t<class_t>::m_instance_count{};
// End of header file
//------------------------------------------------------------------------------
// inherit each class you want to count the number of instaces of
// from the class template specialized for that class.
enter code here
class A :
public instance_counter_impl_t<A>
{
};
class B :
public instance_counter_impl_t<B>
{
};
int main()
{
{
A a1;
B b1;
A a2;
B b2;
}
return 0;
}