How to implement caching in C ++?

Suppose I have a very large std::map< unsigned int, Foo > FooDBone that contains Fooobjects in memory retrieved by their identifier. Now there may be more objects Foothan there is memory available for storing them. Therefore, I would like to have the following construction:

  • retrieves an object Foowith id x fromFooDB
  • if object x is in FooDB, return it
  • If this is not the case, download it from HD, try to save it in FooDBfor future requests
    • enough memory is available: add it to FooDB
    • Out of memory: free up some space by deleting FooDBobjects that are not in use (old request timestamp)

I would like to reserve some memory for FooDB, and I can’t say how many objects Foocan be stored in it, since they differ in size.

Any ideas on how to implement this?

EDIT

My main problem: how can I determine the size std::mapin memory? Of course, all heap objects stored in it included. How to find out when insufficient memory is reached?

+5
source share
2 answers

, , sizeof(). , sizeof() , Foo . , Foo, , , Foo . Foo, , , .

, // , , , . , , , , , "". , , , , -, .

, Foo . , . , , , .

+5

.

Foo FooDB , .

, .

/ , .

, , .

:

typedef shared_ptr<Foo> PFoo;

class Foo
{
    ...
    list<PFoo>::iterator age;
};

typedef map< unsigned int, PFoo > FooDB;
FooDB foodb; 

list<PFoo> ages;

void LoadFoo(PFoo foo)
{
    ages.push_front(foo);
}

void ReadFoo(PFoo foo)
{
    ...
    ages.erase(foo->age);
    ages.push_front(foo);
}

void MakeSpace()
{
    PFoo foo = ages.back();
    ages.pop_back();
    DeleteFoo(foo);
}
+4

All Articles