Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of pointers. BOOST serialization

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.

like image 893
Joan Carles Avatar asked Aug 19 '26 19:08

Joan Carles


1 Answers

You will need to allocate memory for the object pointed to by pItem:

A* pItem = new A;
ar & *pItem;
m_vector.push_back(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.

like image 118
Attila Avatar answered Aug 22 '26 15:08

Attila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!