language: C++11 (gcc-4.7.2)
date: 612 days 15 hours ago
link:
visibility: private
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <vector>
#include <string>
#include <memory>
using namespace std;
 
#define noexcept
 
template<typename TrackType> 
size_t* mem_used() {static size_t s = 0; return &s;}
 
template<class T, class TrackType, class BaseAllocator = std::allocator<T>> 
class TrackerAllocator : public BaseAllocator {
public:
    typedef BaseAllocator base;
    TrackerAllocator() noexcept : BaseAllocator() {}
    TrackerAllocator(const TrackerAllocator& b) noexcept : BaseAllocator(b) {}
    TrackerAllocator(TrackerAllocator&& b) noexcept : BaseAllocator(b) {}
    template <class U, class TT> 
    TrackerAllocator(const TrackerAllocator<U, TT>& b) noexcept : BaseAllocator(b) {}
    ~TrackerAllocator() {}
 
 
    typename base::pointer allocate(typename BaseAllocator::size_type n) {
        BaseAllocator::allocate(n);
        mem_used<TrackType>() += n;
    }
    typename base::pointer allocate(typename BaseAllocator::size_type n, typename base::pointer h=0) {
        BaseAllocator::allocate(n, h);
        mem_used<TrackType>() += n;
    }
    void deallocate(typename BaseAllocator::pointer p, typename BaseAllocator::size_type n) {
        BaseAllocator::deallocate(n);
        mem_used<TrackType>() -= n;
    }
};
 
typedef std::basic_string<char, 
                          std::char_traits<char>,
                          TrackerAllocator<char, string> > trackstring;
typedef std::vector<int, 
                    TrackerAllocator<int, vector<int>> > trackvector;
 
int main() {
    trackstring mystring("HELLO WORLD");
    trackvector myvec(mystring.begin(), mystring.end());
 
    std::cout << *mem_used<string>() << '\n'; //display memory usage of all strings
    std::cout << *mem_used<vector<int>>() << '\n'; //display memory usage of all vector<int>
    //                     ^         ^
    //                     This identifies which memory type from above to look up.
}