c++ - 如何通过 getter 函数序列化包含指针的类?

标签 c++ boost boost-serialization

假设我有一个类A ,其中包含一个私有(private)成员 B const * p ,可通过公共(public)函数 B const& A::get() 访问。如何序列化函数 A 使用 boost save_construct_dataload_construct_data功能?

这是我的尝试(请注意,此示例说明了问题本身,而不是我使用此 get 函数的原因):

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

#include <fstream>

class B
{
public:
    int a;

        //////////////////////////////////
        // Boost Serialization:
        //
    private:
        friend class boost::serialization::access;
        template<class Archive>
        void serialize(Archive & ar,const unsigned int file_version)
        {
            ar & a;
        }
};

class A
{
public:
    A(B const * p) : p(p) {}
    B const& get() const {return *p;}
private:
    B const * p;

    void A::Save(char * const filename);
    static A * const Load(char * const filename);

        //////////////////////////////////
        // Boost Serialization:
        //
    private:
        friend class boost::serialization::access;
        template<class Archive>
        void serialize(Archive & ar,const unsigned int file_version){}
};

namespace boost 
{ 
    namespace serialization 
    {
        template<class Archive>
        inline void save_construct_data(
        Archive & ar, A const * t, unsigned const int file_version
        )
        {
            ar << &t->get();
        }

        template<class Archive>
        inline void load_construct_data(
        Archive & ar, A * t, const unsigned int file_version
        )
        {
            B const * p;
            ar >> p;

            ::new(t) A(p);
        }
    }
}

// save the world to a file:
void A::Save(char * const filename)
{
    // create and open a character archive for output
    std::ofstream ofs(filename);

    // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);

        // write the pointer to file
        oa << this;
    }
}

// load world from file
A * const A::Load(char * const filename)
{
    A * a;

    // create and open an archive for input
    std::ifstream ifs(filename);

    boost::archive::text_iarchive ia(ifs);

    // read class pointer from archive
    ia >> a;

    return a;
}

int main()
{

}

错误是:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const B *' (or there is no acceptable conversion)

最佳答案

您无法序列化临时对象(AFAICT 这是 Boost 限制)。

B const * p = &t->get();
ar << p;

关于c++ - 如何通过 getter 函数序列化包含指针的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19078168/

相关文章:

c++ - 在为 Android 开发时如何在 Eclipse 中获得 C++ 的智能感知?

c++ - 如何访问类对象的每个实例的静态变量值

c++ - UDP端口的低延迟读取

Boost序列化文件结尾

c++ - 错误 C2512 : 'Box' : no appropriate default constructor available

c++ - std::vector<double> 缩小以适应?

c++ - 我可以在单独的线程上刷新我的 ofstream 吗?

c++ - 针对 Boost.Log 的 g++ 静态链接错误

c++ - boost::serialization 存档版本介于 v1.59 和 v1.60 之间

c++ - 反序列化没有默认构造函数的类型的STL容器