Question

I have code looking something like this:

struct DataStruct
{
//  some fields here
};

class C1
{
public:
    C1(size_t n)
    {
        ptrData = new DataStruct[n];
        ptrPtrs = new DataStruct*[n];
        for(size_t i=0;i<n;i++)
            ptrPtrs[i] = &ptrData[i];
    }

    virtual ~C1() 
    {
        delete[] ptrData;
        delete[] ptrPtrs;
    }

    DataStruct* ptrData;
    DataStruct** ptrPtrs;
};

and need it to be serialized preferably by boost::serialization. I have not found ways to save dynamically allocated arrays except saving it item by item in loop. But not sure how to save second array - array of pointers. Is it possible to do it more or less convenient way in boost?

Was it helpful?

Solution

It is impossible for boost to know the number of elements as all you have is a pointer. The heap manager knows how many elements to delete when you call delete[] but it is not made available to code like boost::serialize

Of course your best bet is to use a std::vector in the first place, but failing that, create a "wrapper" class that can be used for serialization, both inbound and outbound.

If we call it ArrayWrapper and template it

template< typename T >
struct ArrayWrapper
{
   T* data = nullptr;
   size_t size = 0;
   ArrayWrapper() = default;
   ArrayWrapper( T* data_, size_t size_ ) : data( data_ ), size( size_ ) {}
};

Now you can serialize one from a pointer and the known size by first writing the size, then each item.

When serializing back, you first read the size, then allocate the number of objects and then reading them in.

Of course you need to manage your memory and using std::vector is a far better option.

In general, you do not store "pointers" you store the data they point to. when read back out of the archive, you are not going to get the same pointers that went in, you will get the same data back.

For that purpose, you actually just archive the outer one (array of pointers) and get it to call ArrayWrapper on the inner one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top