仅在 Windows 上运行的进程之一的内存占用比以前使用更多的内存,我想知道内存中存在哪些所有 C++ 对象,以查看是否有额外的分配? 我可以使用 WinDbg for .NET 应用程序来找到它。但是,是否可以在不购买内存分析器商业应用程序的情况下为 C++ 做到这一点?
如果您买不起工具,您也许可以使用 mixin 代码向每个类添加实例计数,如下所示(当然您可能希望输出到日志文件)。我现在时间不多了,所以如果您有疑问,请询问他们,我稍后再回复。
#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 << "\n";
}
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 << "\n";
}
};
//------------------------------------------------------------------------------
// 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;
}