Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does an std::string field in a struct gets written to an std::fstream?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading