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?
You mix std::basic_ostream::write
and printf
, which are unrelated. write
is for unformatted output of character/byte data, whereas printf
is c 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.