I am using std::string in my MFC application and I want to store it in doc's Serialize() function. I don't want to store them as CString because it writes its own stuff in there and my goal is to create a file that I know the format of and can be read by other application without needing CString. So I would like to store my std::strings as 4 bytes (int) string length followed by buffer of that size containing the string.
void CMyDoc::Serialize(CArchive& ar)
{
std::string theString;
if (ar.IsStoring())
{
// TODO: add storing code here
int size = theString.size();
ar << size;
ar.Write( theString.c_str(), size );
}
else
{
// TODO: add loading code here
int size = 0;
ar >> size;
char * bfr = new char[ size ];
ar.Read( bfr, size);
theString = bfr;
delete [] bfr;
}
}
The above code is not great and I have to allocate a temp bfr to read the string. First can I read the string directly into std::string without the temp buffer? Secondly can I overload the << buffer for std::string / CArchive so I can simply use ar << theString? Overall is there a better way to read/write std::string using CArchive object?