[serialization] bug? serializing a vector resets ignored element members
Hi If I serialize a struct, while ignoring one of its members, the member retains its value. I understand that this is the inteded serialization semantics - what you ignore for reading and writing remains intact. However, if I do this with a vector, the ingored members of its elements get reset to their "default" values. I'm too lazy to pore over the sources, but I'm guessing this might be happening because the implementation of vector serialization calls its constructor (and assignment?) where a resize could probably be better. Here is the specific code I boiled down the manifestation of this feature/bug to: // creates writes "remove_me" file #include <iostream> #include <fstream> #include <vector> #include <boost/filesystem/fstream.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> struct s { s() : i(0), j(0) {} s(int i, int j) : i(i), j(j) {} int i, j; private: friend class boost::serialization::access; template<typename Archive> void serialize(Archive& ar, const unsigned version) { // ignore j ar & i; } }; struct v { v(const s& x) : data(5, x) {} std::vector<s> data; void write(const char* name) const { std::ofstream out(name); boost::archive::text_oarchive ar(out); ar << *this; } void read(const char* name) { std::ifstream in(name); boost::archive::text_iarchive ar(in); ar >> *this; } private: friend class boost::serialization::access; template<typename Archive> void serialize(Archive& ar, const unsigned version) { ar & data; } }; int main() { using namespace std; const char name[] = "remove_me"; s si(1, 2); // j == 2 v vi(si); vi.write(name); vi.read(name); std::cout << vi.data[0].j << std::endl; // j == 0 }
n.torrey.pines@gmail.com wrote:
I'm too lazy to pore over the sources, but I'm guessing this might be happening because the implementation of vector serialization calls its constructor (and assignment?)
Good guess - probably correct
where a resize could probably be better.
Hmm - maybe or maybe not. That would raise the issue of what to do about std::map and others that can't be "fixed" this way. Fixing vector would leave a situation where behavior varied according to what kind of collection the instance was an element of. Still an interesting question. I suspect it hasn't come up until now as the "un serialized members" are usually not important enough to serialize not important enough to save the values. If this behavior is important to you, I think the best would be to implement your own variation of serialization for std::vector. I'm sure you would find this very easy using the current implementation as a basis. Robert Ramey
participants (2)
-
n.torrey.pines@gmail.com
-
Robert Ramey