You can't use the read()/write() function with a structure when you have non-trivial member variables like std::strings.
When writing a std::string using the write() method you'll write a pointer not the actual data. Plus since a string has a variable length you need to preserve the length of the string so you know how many bytes were written to the file.
When reading to a std::string the string must have enough room reserved to hold the data.
but that wasn't my question, my question is "why when I declare and define a string within the main() function, with the same program, everything runs perfect?"
This is weird, the above program (the one in the comments) don't crash on my pc, and I tested it with 3 diferent IDES.
Everything began when i wanted to test if there was an native and easy way to serialize objects (of course i was just playing with c++).
I thought that a string wouldn't work in this case. So i made the program above (in the comments) and it worked.
So I thought again "it may have worked because everything is in the same scope, it is saving a pointer to the string within the intance of the aggregate class i made".
So i wanted to see what happened if I saved the object within a file, and then, destroy the object (so the string frees), that's what I did and then, made the program that is in the top of this topic.
Everything went bad, (that's what I expected). but them I randomly put
string a = "secreto";//line 23
And it worked.
so, I wonder, why putting that within the code, makes someway the pointer stored in the file avaliable again?, i mean, that don't make sense at all.
so, I wonder, why putting that within the code, makes someway the pointer stored in the file avaliable again?, i mean, that don't make sense at all.
Since you're not reading what you think you are it is pretty much pure luck. If, after you write the file the first time, you remove the write() call and re-run the program, you will possibly be able to see what is wrong. You're not writing the string to the file, you're writing the address of the string into the file.