Boost logo

Boost Users :

From: Anders Sundman (anders.sundman_at_[hidden])
Date: 2007-02-01 15:31:44


Thank you for your answer.

Unfortunately, I don't write the classes I have to serialize :)

I've managed (with the help of Dave Nay) to distill my helper function
to the more compact:

template<class T, class Archive>
static void serializeBuf(Archive & ar, T * & data, size_t & elemCnt) {
   ar & elemCnt;

   if(elemCnt > 0) {
     if (Archive::is_loading::value) {
       assert(data == 0); // Must have null target to avoid double alloc
       data = new T[elemCnt];
     }

     assert(data != 0); // Can't be null now, about to write
     ar & boost::serialization::make_binary_object(data, elemCnt *
sizeof(T));
   }
}

Thank you for pointing out the danger (also present above) in T that may
not be serializable.

// Anders

Robert Ramey skrev:
> Your solution below would likely work. These days I would expect find
> the T* / size pair replaced with something like std::vector<T *> tarray
> in which case you could have just used:
>
> ar & tarray
>
> But you're solution is a natural way to proceed under the circumstances.
>
> BUT - it presumes that T can be serialized as a binary which is not
> portable and not generally true.
>
> A general solution would be to use a loop which
>
> ...
> ar & t[i]
>
> For examples, look at the implementation of serialization for collections
> as included in the library.
>
> Robert Ramey
>
> Anders Sundman wrote:
>> Ok, my bad. I've found the docs:
>>
>> http://www.boost.org/libs/serialization/doc/serialization.html#splitting
>>
>> But the general question remains, what to do with dynamic data?
>>
>> It's often the case that I find a T* and a size in classes. I've been
>> thinking about introducing some kind of convenience functions for
>> this. Perhaps something along these lines:
>>
>> template<class T, class Archive>
>> void saveBuf(Archive & ar, const T * buf, size_t size) {
>> bool isNull = (buf == 0);
>> ar << size;
>> ar << isNull;
>> if (!isNull)
>> ar.save_binary(buf, size * sizeof(T));
>> }
>>
>> template<class T, class Archive>
>> void loadBuf(Archive & ar, T *& buf, size_t & size) {
>> bool isNull;
>> ar >> size;
>> ar >> isNull;
>>
>> if (buf != 0) {
>> delete buf;
>> buf = 0;
>> }
>>
>> if(!isNull) {
>> buf = new T[size];
>> ar.load_binary(buf, size * sizeof(T));
>> }
>> else {
>> buf = 0;
>> }
>> }
>>
>> What do you thing about that? Any obvious problems? Are there perhaps
>> already something like this in the library?
>>
>> // Anders Sundman
>>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net