0

Why non-const reference here?

template<class T>
const nvp< T > make_nvp(const char * name, T & t);

The reason i'm asking is that i have a structure with public fields and i need to make them private and use accessors instead. So i would like to know if i'm allowed to use temporary variable and pass them to make_nvp or i need to befriend my serializer with the data structure.

// option 1
auto a = data.getA();
ar & make_nvp("A", a);

// option 2
ar & make_nvp("A", data._a); // _a is private, but serializer is friend

I don't know what is this ar because it's a templated parameter, so in some cases it could make use of this non-constness and save it for later use and then option 1 is problematic.

Yola
  • 18,496
  • 11
  • 65
  • 106
  • 1
    In boost archive, you can use a single function for both serialization and deserialization. This is achieved by using the archive as template argument - it can be an output archive that serializes your structure or an input archive that loads your struct. For deserialization the function needs a non-const reference to store the deserialized value and that's why `make_nvp` needs a non-const reference. – pschill Aug 18 '17 at 08:46
  • @pschill i like your comment. You might want to turn into an answer and i will accept it. – Yola Aug 18 '17 at 08:48

2 Answers2

3

In boost archive, you can use a single function for both serialization and deserialization. This is achieved by using the archive as template argument - it can be an output archive that serializes your structure or an input archive that loads your struct from some file. For deserialization the function needs a non-const reference to store the deserialized value and that's why make_nvp needs a non-const reference.

Coming back to your question: Option 2 makes more sense, because option 1 breaks the deserialization.

pschill
  • 5,055
  • 1
  • 21
  • 42
0

Option 1 breaks object tracking and is fine as long as you don't serialize any pointers to data._a or it's interior.

yuri kilochek
  • 12,709
  • 2
  • 32
  • 59