title: String serialization in C++
body: <p>I have a following class fields:</p>
  
  <pre><code>int _number; 
  string _name; 
  int _amount;  
  bool _isAvailable; 
  double _price; 
  int _storageTime; 
  
  int _entranceDay; 
  int _entranceMonth;
  int _entranceYear;
  </code></pre>
  
  <p>How shall I serialize/deserialize an object of that class?</p>
  
  <p>I tried this:</p>
  
  <pre><code>    void Serialize() {
          ofstream ofs("tmp.bin", ios::binary | ios::out);
          ofs.write((char*)&amp; _number, sizeof(int));
          ofs.write((char*)&amp; _amount, sizeof(int));
          ofs.write((char*)&amp; _isAvailable, sizeof(bool));
          ofs.write((char*)&amp; _price, sizeof(double));
          ofs.write((char*)&amp; _storageTime, sizeof(int));
          ofs.write((char*)&amp; _entranceDay, sizeof(int));
          ofs.write((char*)&amp; _entranceMonth, sizeof(int));
          ofs.write((char*)&amp; _entranceYear, sizeof(int));
          int stringSize = _name.size();
          ofs.write((char*)&amp; stringSize, sizeof(int));
          for (int i = 0; i &lt; stringSize; ++i) {
              char c = _name[i];
              ofs.write(&amp;c, sizeof(char));
          }
          ofs.close();
      }
  </code></pre>
  
  <p>And this for Deserialization:</p>
  
  <pre><code>    void Deserialize() {
          ifstream ifs("tmp.bin", ios::binary | ios::in);
          ifs.read((char*)&amp; _number, sizeof(int));
          ifs.read((char*)&amp; _amount, sizeof(int));
          ifs.read((char*)&amp; _isAvailable, sizeof(bool));
          ifs.read((char*)&amp; _price, sizeof(double));
          ifs.read((char*)&amp; _storageTime, sizeof(int));
          ifs.read((char*)&amp; _entranceDay, sizeof(int));
          ifs.read((char*)&amp; _entranceMonth, sizeof(int));
          ifs.read((char*)&amp; _entranceYear, sizeof(int));
          int stringSize;
          ifs.read((char*)&amp; stringSize, sizeof(string));
          string name;
          for (int i = 0; i &lt; stringSize; ++i) {
              char c;
              ifs.read(&amp;c, sizeof(char));
              name += c;
          }
          _name = name;
          ifs.close();
      }
  </code></pre>
  
  <p>Serialization doesn't throw any exception. As for deserialization - it throws an exception: "Run-Time Check Failure #2 - Stack around the variable 'ifs' was corrupted." 
  Debugger shows, that all the fields were deserialized correct expect for the string field.
  So, how to serialize/deserialize a string correctly?</p>