【问题标题】:serialization of class with const members using Boost使用 Boost 对具有 const 成员的类进行序列化
【发布时间】:2018-11-09 05:17:06
【问题描述】:

考虑下面的代码sn-p

class tmp1
{
    const int a_;
    const double b_;   
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int ver)
    {
        ar & a_ & b_ ;
    }

public:
    tmp1(const itype a , const ftype b) : a_(a), b_(b)
    {}
};

我可以通过这样做将对象写入文件

tmp1 t1(2, 10.0);    
std::string filename ="D:/Temp/demofile.txt";
std::ofstream ofs(filename);    
boost::archive::text_oarchive oa(ofs);
oa<<t1;

我想通过读取文件来构造tmp1 的另一个实例。理想情况下,我希望这发生在第二个构造函数中,它接受文件名并构造它。我该如何做到这一点?

我试过了

tmp1 t2(10, 100.0);
    std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
ia>>t2;

但是 VS2012 编译失败并显示以下消息

archive/detail/check.hpp(162): error C2338: typex::value
4>          \boost\boost_1_67_0\boost/archive/detail/iserializer.hpp(611) : see reference to function template instantiation 'void boost::archive::detail::check_const_loading<T>(void)' being compiled
4>          with
4>          [
4>              T=const itype
4>          ]

我认为这是因为成员是 const。我认为 boost 会抛弃 const 限定符,但似乎并非如此。

【问题讨论】:

    标签: c++ serialization boost constructor constants


    【解决方案1】:

    您正在寻找的是文档中的“非默认构造函数”:

    https://www.boost.org/doc/libs/1_67_0/libs/serialization/doc/index.html

    你需要为

    写一个重载
    template<class Archive, class T>
    void load_construct_data(
        Archive & ar, T * t, const unsigned int file_version
    );
    

    所以对于 Foo 类,例如,它由一个整数和一个字符串构成,您可以提供:

    template<class Archive>
    void load_construct_data(
        Archive & ar, Foo * t, const unsigned int file_version
    )
    {
        int a;
        std::string b;
        ar >> a >> b;
        new (t) Foo(a, std::move(b));
    }
    

    【讨论】:

    • 谢谢!但这可能会导致错误,因为读写例程不同,对吗?为什么它比ar &amp; const_cast&lt;int &amp;&gt;(a_) &amp; const_cast&lt;double &amp;&gt;( b_) ; 更受欢迎?
    • @user6386155 这可能取决于您自己的喜好
    • 有一天你要教我如何通过提升答案获得如此多的支持:)
    • @RichardHodges 方法ar &amp; const_cast&lt;int &amp;&gt;(a_) 我在 boost 文档中看到了它。但它安全吗?我觉得这可能会导致未定义的行为
    • @user6386155 通过 const_cast 访问对象仅在对象最初是可变的情况下才有效。在你的情况下它不是,所以你提出的是未定义的行为。此外, cast 方法要求 Foo 是默认可构造的。这对于具有 const 成员的对象是不合逻辑的。
    猜你喜欢
    • 2018-02-02
    • 2014-06-15
    • 2014-06-07
    • 1970-01-01
    • 2012-01-30
    • 2019-02-19
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多