且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

反序列化构造函数无法正确读取数据

更新时间:2022-12-14 17:24:31

你不应该直接调用 serialize 方法:operator >> for a archive do way 不仅仅是调用 serialize;根据存档的类型,它首先需要加载前导码等.您可以通过调试器逐步执行或检查 test.archive 中的内容来验证这一点,就像

You shouldn't call serialize methods directly: operator >> for an archive does way more than just calling serialize; depending on the type of archive it first needs to load a preamble etc. You can verify this by stepping through with the debugger, or by checking what's inside test.archive, it is something like

22 serialization::archive 12 0 0 1.000000000e+000 2.000000000e+000

所以在构造一个 text_iarchive 之后,对 operator & 的前两次调用会碰巧看到那些 2 0 在那里实际数据.

so right after constructing a text_iarchive the first two calls to operator & will happen to see those 2 0's in there instead of the actual data.

你的构造函数应该是:

template<class TArchive>
Point(TArchive& archive)
{
  archive >> *this;
}

编辑这里是如何使用 SFINAE 确保仍然可以调用复制构造函数的示例

Edit here's an example of how to use SFINAE to make sure the copy constructor can still be invoked

Point( const Point& rh ) :
  mX( rh.mX ),
  mY( rh.mY )
{
}

template<class TArchive>
Point( TArchive& archive,
       std::enable_if_t< !std::is_same< TArchive, Point >::value >* = nullptr )
{
  archive >> *this;
}