0

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?

  • "And Here is how i write it to an fstream" you do it wrong, that can be done only with trivially copyable classes (aka POD). Your class is not. – Slava Aug 31 '22 at 15:41
  • Yes, you are right but that was just an example. I just wanted to know how that string field is written to the fstream. @DXPower explained it very clearly though. – ThewyRogue99 Aug 31 '22 at 15:53
  • "I just wanted to know how that string field is written to the fstream." Not sure what that knowledge will give you. When you write incorrect programs you may see all kind of garbage on the output. Some of that may be related to your data, but it does not make your program any close to be correct. – Slava Aug 31 '22 at 15:56

1 Answers1

0

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.

DXPower
  • 391
  • 1
  • 11
  • Yes, I tried using longer string and now it only writes the address. I didn't know about short string optimization before. Thanks for letting me know. – ThewyRogue99 Aug 31 '22 at 15:55