gpt4 book ai didi

c++ - std::containers 的日志分配器?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:31 25 4
gpt4 key购买 nike

X:我需要知道程序的每个部分使用了多少内存。我的程序经常使用 C++ std 库。特别是,我想知道每个对象使用了多少内存。

我是怎么做的:要记录some_vector的消耗,只需写

my::vector<double,MPLLIBS_STRING("some_vector")> some_vector;

在哪里

namespace my {
template<class T, class S>
using vector = std::vector<T,LoggingAllocator<T,S>>;
}

登录分配器实现如下:

template<class T, class S = MPLLIBS_STRING("unknown")> struct LoggingAllocator {
// ... boilerplate ...

pointer allocate (size_type n, std::allocator<void>::const_pointer hint = 0) {
log_allocation(boost::mpl::c_str<S>::value);
// allocate_memory (I need to handle it myself)
}
void destroy (pointer p) ; // logs destruction
void deallocate (pointer p, size_type num); // logs deallocation
};

问题:是否有更好的方法以通用方式获得此行为?我的意思是更好,更简单,更好,不依赖于 boost::mplmpllibs::metaparse,...理想情况下我只想写

my::vector<double,"some_vector"> some_vector;

并完成它。

最佳答案

虽然可能不是“更通用”,但如果您不想自己处理所有分配,您可以继承标准分配器 std::allocator :

template<class T, class S = MPLLIBS_STRING("unknown"), class Allocator = std::allocator<T>>
struct LoggingAllocator : public Allocator {
// ...
};

allocate/destroy/deallocate 函数中进行日志记录,然后调用父方法:

pointer allocate (size_type n, std::allocator<void>::const_pointer hint = 0) {
log_allocation(boost::mpl::c_str<S>::value);
return Allocator::allocate(n, hint);
}

但是请注意,std::allocator 并不是真正为继承而设计的,例如它没有虚拟析构函数。

关于c++ - std::containers 的日志分配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14956176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com