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?
You could build an inplace CString from your stl string and serialize that. Something like:
CString c_string(my_stl_string.c_str();
ar << c_string;
You could put this in a global operater overload so it can you can just
ar << my_c_string;
from anywhere eg:
CArchive& operator<<(CArchive rhs, string lhs) {
CString c_string(lhs.c_str());
rhs << c_string;
}
Try:
theString.resize(size);
ar.Read(&theString[0], size);
Technically &theString[0]
is not guaranteed to point to a contiguous character buffer, but the C++ committee did a survey and found that all existing implementations work this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With