I have an application where I need some data to persist, so I thought about object serialization. I found a nice example here. Following it, this is what I came up with:
std::stack <std::string> cards;
cards.push("King of Hearts");
std::ofstream ofs("<location>", std::ios::binary);
ofs.write((char *)&cards, sizeof(cards));
ofs.close();
Then I am trying to read the data:
std::stack<std::string> inp;
std::ifstream ifs("<same_location>", std::ios::binary);
ifs.read((char *)&inp, sizeof(inp));
However the app is crashing at the last line (for some reason, due to my Qt settings, I am unable to debug currently). What can be the possible error, and how do I fix this?
Short answer is: you cannot serialize stack in the same way as the article describes. I'd say that you can only serialize PODs that way. The problem here is that the data you want to write is not stored continuously in the memory and by using
ofs.write((char *)&cards, sizeof(cards));
you are not not taking into account the pointers to other places in the memory.Try this experiment: how come that sizeof(cards) do not change when you add more and more data to it?