Question

I have a class with a member clientCache:

    public:
        LRUCache<string, string>* clientCache;

The cache is initated by:

    clientCache = new LRUCache<string, string>(3);

    //Reset cache to stored values if exist:
    ifstream ifs(this->cachePath.c_str(), ios::binary);

    // Verify that file exists
    if(ifs.good()){
        ifs.read((char *)&this->clientCache, sizeof(this->clientCache));
        printf("Persistent cache file loaded");
    }

In the destructor:

    ofstream ofs(this->cachePath.c_str(), ios::binary);
    ofs.write((char *)&this->clientCache, sizeof(this->clientCache));
    printf("Persistent cache file written with:");
    printf((char*)&this->clientCache); //-> Nothing gets printed 

Try to load back the file written in the previous step fails:

    ifstream ifs(this->cachePath.c_str(), ios::binary);
    // Verify that file exists
    if(ifs.good()){
        ifs.read((char *)&this->clientCache, sizeof(this->clientCache));
        printf("Persistent cache file loaded");
    }

Should the printed output really be empty? Is this a sign that the saving fails. Does the content (methods/members) of LRUCache class matter, i.e. will i be more successfull if i try to store all key values instead of the data of the entire instance?

Was it helpful?

Solution

You mix std::basic_ostream::write and printf, which are unrelated. write is for unformatted output of character/byte data, whereas printf is style formatted output.

Furthermore, you cannot write a class to disk and read it back that way, because the binary layout of an object, especially the address of the virtual function table, may differ from one run of the program to another.

In this special case, you even write and read only the pointer to dynamic memory. When you read the pointer back, the memory it is supposed to point to, might not be allocated anymore.

Better write an appropriate input and output operator, which reads and writes the needed members only.

OTHER TIPS

printf((char*)&this->clientCache); //-> Nothing gets printed 

I think this does not do what you want. Assuming clientCache is a pointer

LRUCache<string, string>* clientCache;

what happens is printing the pointer value (which shouldn't work), not the object stored in it.
Anyway, a better way to do it is using the << and >> operators to write and read the object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top