0

I had something simple like this POD structure...

struct Actor
{
    string name; 
    int hp;
};

Later on, for simplicity sake here, I saved the structure to file using...

 ofstream_obj.write((char *)&PC, sizeof(Actor));

Then, I tried reading the file back. It loaded in the data, but upon exit it gave an ugly exception, pointing at xutility at the line of: *_Pnext != 0

inline void _Container_base12::_Orphan_all()
    {   // orphan all iterators
 #if _ITERATOR_DEBUG_LEVEL == 2
    if (_Myproxy != 0)
        {   // proxy allocated, drain it
        _Lockit _Lock(_LOCK_DEBUG);

        for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
            *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)
            (*_Pnext)->_Myproxy = 0;
        _Myproxy->_Myfirstiter = 0;
        }
 #endif /* _ITERATOR_DEBUG_LEVEL == 2 */
    }

After giving up, I changed the std::string to char name[20], tried the whole thing again, and it worked fine. Is there something different about loading back std::string? Is it not calling std::string's copy constructor?

0

1 Answer 1

3

std::string holds a pointer internally to the actual string data which is malloced on the heap.

write(char*, size_t) doesn't consider internal types (and associated copy constructors) AT ALL. This means that you were writing a pointer to a file, which never works.

to fix it properly you would need actual serialization that writes the string out properly (like write length and then the data)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.