提问人:Brajesh 提问时间:9/27/2023 更新时间:9/27/2023 访问量:119
有没有办法知道正在运行的进程的 C++ 对象计数及其类型?[关闭]
Is there a way to know the C++ objects count and their types of a running process? [closed]
问:
闭。这个问题正在寻求有关书籍、工具、软件库等的建议。它不符合 Stack Overflow 准则。它目前不接受答案。
我们不允许提出有关书籍、工具、软件库等建议的问题。您可以编辑问题,以便用事实和引文来回答。
上个月关闭。
仅在 Windows 上运行的一个进程的内存占用比以前使用更多的内存,我想知道哪些所有 C++ 对象都在内存中,以查看是否有额外的分配? 我可以将 WinDbg 用于 .NET 应用程序来查找它。但是,是否可以在不购买内存分析器商业应用程序的情况下为 C++ 做到这一点?
答:
1赞
Pepijn Kramer
9/27/2023
#1
如果你买不起工具,你可以使用 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;
}
评论