I have a complicated struct with sub-structs to store the settings of my program. This structs contain some std::vectors. I save the struct with this easy function:
void saveSettings(std::string filename)
{
std::ofstream file(filename, std::ios::binary);
if (file.is_open())
{
file.write(reinterpret_cast<const char*>(&Settings), sizeof(Settings));
file.close();
}
else
std::cout << "Error saving Settings.dat" << std::endl;
}
When the program loads, it reads the settings-file and stores the data in my settings-struct again. That would work fine if not for the vectors. What causes problems is that the state of the vectors is restored, including the data-pointer, but the data-array itself does no longer exist. As soon as I do a resize or something else that changes the array-size, the vector tries to delete the old data-array which of course fails (and of course I cannot read/write to any elements).
I neither need nor want that data in my settings-file. I could find another way to store the settings-struct (without the vectors), but I think that would be much more complicated and would make other things problematic. Is there a way to "reset" a vector or maybe give it a valid data-array?
One thing that actually does work is this:
struct VectorHack
{
size_t test1;
size_t test2;
size_t test3;
size_t test4;
};
VectorHack& hackedVec = reinterpret_cast<VectorHack&>(vec);
//hackedVec.test1 = 0;
hackedVec.test2 = 0;
hackedVec.test3 = 0;
hackedVec.test4 = 0;
This seems to "reset" the vector. It doesn't seem to make a difference whether or not I set test1 to 0, but I have no idea, what this number is for (it is different, every time a new vector is created).
Of course this is a very dirty hack, that could cause problems and that probably will not be portable. Can anyone point me to a better and easy solution to either "reset" the vectors or store the structs without them? I tried emptying the vectors before they are stored (and that seems to set the data-pointer to nullptr), but the program still crashes as soon as I do a resize.