How can I implement an "Object Buffer" which can limit memory size?

  architecture, c++, memory, memory-management

Firstly, I know that many modern softwares have features like "limit the memory usage" of some particular part. These softwares may use OS-level API or memory pool or other advanced techniques I don’t know to implement this kind of features.
But so far I’m writing on a small program so I want to be as simple as possible, here’s my problem:

Suppose I have a class with some complex STL data structures

class ComplexStructure {
private:
    std::map<AAA, BBB> struct1;
    std::vector<CCC> struct2;
    std::unordered_map<DDD, EEE> struct3;
public:
    void generate_some_data();
    void delete_some_data();
};

genreate method can insert some data into these structures, delete method can erase some data from these structures. Obviously they can change the memory usage.

Now I have a "buffer" class which specifically designed for storing ComplexStructure (may also partially act as a "factory"). It has a max_size to limit # of bytes of these ComplexStructures

class ComplexStructureBuffer {
private:
    size_t max_size;
    size_t size;
    std::list<ComplexStructure> list;
public:
    bool is_full();
    ComplexStructure& create(params...);
    void erase(ComplexStructure&);
}

My question is:

  1. How can I know the accurate memory usage of ComplexStructure? Of course 100% accurate is impossible, but at least we should be able to count the bytes that are allocated by new operator, right?
  2. How can I "link" ComplexStructure to this "buffer" in some way (NOTE there may have multiple buffers, so can’t use a global parameter), so that when call generate or delete method, they can update size member variable and know if buffer is full?

Currently the only solution I have is to declare const size_t& max_size and size_t& size in ComplexStructure. When generate or delete data, use sizeof and # of items to estimate memory usage. This solution is very ugly and horribly inaccurate, it shouldn’t be that way.

Addition solution may be somehow "hook" the allocator used in every STL container, so that whenever they allocate memory, we can know the actual size. But I don’t know how to implement.

Seems like not only c++, all programming languages don’t have this kind of features. There should be something wrong, is this demand so rare or my design is completely broken?

Source: Windows Questions C++

LEAVE A COMMENT