Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overload CArchive << operator to work with std::string?

Tags:

c++

stl

mfc

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?

like image 711
zar Avatar asked Sep 16 '11 14:09

zar


2 Answers

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;
}
like image 197
Ricibob Avatar answered Oct 14 '22 02:10

Ricibob


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.

like image 33
Mark Ransom Avatar answered Oct 14 '22 03:10

Mark Ransom