I want to serialize/deserialize using BOOST the values (not the pointers) of objects in the following vector:
std :: vector <A*> m_vector;
To serialize I use the following code:
int nItems = m_vector.size();
ar & nItems;
std::for_each(m_vector.begin(), m_vector.end(), [&ar](A* pItem) {
ar & *pItem;
});
And to deserialize:
int nItems;
ar & nItems;
for (int i = 0; i < nItems; ++i) {
A* pItem;
ar & *pItem; ///////////// Run-Time Check Failure #3
m_vector.push_back(pItem);
}
But when I run the program I get the following error:
Run-Time Check Failure # 3 - The variable 'pItem' is Being Used without Being initialized.
What am I doing wrong?
Thank you.
You will need to allocate memory for the object pointed to by
pItem
:The error was because although you had a pointer, there was no object at the memory location where the pointer pointed to -- the value of the pointer was garbage (uninitialized pointer).
Don't forget to call
delete
when you no longer need the object pointed to by the pointer in the vector to preven memory leak. Better yet, use a smart pointer (e.g.boost::shared_ptr<>
) to ensure the memory is deallocated when no longer accessible.