How do I specify the links between pointers and source data?

Question:

When serializing in boost :: serialization, you can write the vector std::vector<int> base;

And then restore it. You can write a pointer to this vector and restore it in the same way. You can write std::vector<int*> base vector with pointers and also restore by value.

But how to do (if possible) so that during serialization the connections between the original data and pointers to them are preserved.

That is, when restoring

std::vector<int> <<------------------------------------------\
                                                             |
в контейнере `std::vector<int*>` хранились указатели на ---> |

This can be done manually, but it is the boost capabilities that are of interest.

#include <boost/iostreams/stream.hpp> 
#include <boost/iostreams/stream_buffer.hpp>

#include <boost/serialization/array.hpp> 
#include <boost/serialization/string.hpp> 
#include <boost/serialization/vector.hpp>

#include <boost/archive/xml_oarchive.hpp> 
#include <boost/archive/xml_iarchive.hpp> 
#include <boost/serialization/export.hpp> 
#include <iostream> 
#include <fstream>

int main()
{
std::system("chcp 1251");

// Исходные данные
std::vector<int> base;
base.push_back(77);

// вот здесь хранятся указатели на base
std::vector<int*> links;
links.push_back(&base[0]);

/// Здесь запись и востановление base
//
{
std::ofstream OA("file.txt");
std::cout << "\nдо base[0]=" << base[0];
boost::archive::xml_oarchive oa(OA);
oa << BOOST_SERIALIZATION_NVP(base);
}
// очистка
base.clear();

{
std::ifstream IA("file.txt");
boost::archive::xml_iarchive ia(IA);
ia >> BOOST_SERIALIZATION_NVP(base);
std::cout << "\nпосле base[0]=" << base[0];
}

#ifdef здесь_ошибка_компиляции 
// error C2228: выражение слева от ".serialize" должно представлять класс, структуру или объединение

/// Здесь запись и востановление links
//
{
std::ofstream OA("file.txt");
std::cout << "\nдо base[0]=" << links[0];
boost::archive::xml_oarchive oa(OA);
oa << BOOST_SERIALIZATION_NVP(links);
}
// очистка
links.clear();

{
std::ifstream IA("file.txt");
boost::archive::xml_iarchive ia(IA);
ia >> BOOST_SERIALIZATION_NVP(links);
std::cout << "\nпосле base[0]=" << links[0];
}
#endif

Answer:

First, it is highly undesirable to work with pointers to objects in std::vector , because it does not guarantee that data will not be moved in memory while the program is running. Your pointers will be broken, and the program will crash or make trouble. Use std::list instead, it is guaranteed not to break your pointers.

Secondly, first loading the array and then creating an array with references to it is an atypical situation, and most likely it is not implemented in Boost. It is better and safer to implement this manually.

And before trusting Boost to work with pointers, think about who will clean up the memory. If you load data in the form of pointers from a file, you will have to clean it up manually.

Scroll to Top
AllEscort