Here is an example struct:
struct Person
{
std::string Name;
int Age;
};
And Here is how i write it to an fstream:
Person p;
p.Name = "Mike";
p.Age = 21;
stream.write((char*)&p, sizeof(p));
As you can see above I write my Person variable to an fstream using write() function. Person’s name is written to the stream as "Mike" but when i use it with a const char* it just writes the address to the string. What i do not understand is this: How does fstream write std::string’s value but not the pointer to the string itself?
>Solution :
There is no special magic here. Try a larger string (say a few lines of lorem ipsum), and you will find the same thing happens as const char* (with a few extra data points like size and capacity).
This behavior comes from the Small String Optimization. For short strings, the characters are actually stored inside the std::string storage itself instead of keeping a pointer to a char buffer storage. Once the string gets large enough, this inline buffer is replaced with a pointer to a larger buffer somewhere else in memory.
What are the mechanics of short string optimization in libc++?
In terms of your code, I would make a special routine for your Person class to write the contents to a binary buffer. First it would write the age, then it would write the string via std::string‘s c_str() and size() member functions.