即使具有适当的分面,非有限浮点数的反序列化也会失败

Deserialization of non-finite floating-point numbers fails even with appropriate facets

本文关键字:浮点数 反序列化 失败      更新时间:2023-10-16

我需要使用 Boost.Serialization 来序列化浮点数。由于 NaN 和无穷大无法从输入流中本机读取,因此我正在尝试使用 boost/math/special_functions 中的分面。我已经在我的平台上使用类似于我们在这里找到的示例的代码测试了它们:http://www.boost.org/doc/libs/1_50_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fp_facets/intro.html但是,以下代码仍然无法正确反序列化非有限浮点值(引发异常,说明为"输入流错误")。

#include <limits>
#include <locale>
#include <sstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/math/special_functions/nonfinite_num_facets.hpp>
#include <boost/serialization/nvp.hpp>
struct Data {
        float f;
        Data() : f(std::numeric_limits<float>::quiet_NaN()) {}
        template <class Archive>
        void serialize(Archive & ar, unsigned const)
        {
                ar & BOOST_SERIALIZATION_NVP(f);
        }
};
void test()
{
        using namespace boost::archive;
        Data d;
        std::ostringstream oss;
        xml_oarchive oar(oss);
        oar << BOOST_SERIALIZATION_NVP(d);
        //std::cout << oss.str() << std::endl;
        std::istringstream iss(oss.str());
        std::locale const new_loc(iss.getloc(), new boost::math::nonfinite_num_get<char>);
        iss.imbue(new_loc);
        xml_iarchive iar(iss);
        iar >> BOOST_SERIALIZATION_NVP(d);
        std::cout << d.f << std::endl;
}

我做错了什么吗?我的 Boost 版本或平台有问题吗?有没有更好的解决方案?任何帮助将不胜感激。

我通过阅读以下实施说明找到了解决方案:http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/implementation.html#charencoding

使用默认标志构造存档时,流的区域设置会更改以解决字符编码问题,但可以使用标志boost::archive::no_codecvt禁用此机制。

如果我更换行

xml_iarchive iar(iss);

xml_iarchive iar(iss, no_codecvt);

然后它起作用了。