且构网

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

使用私有成员促进派生类的序列化

更新时间:2022-10-18 15:07:37

首先,对获取用于非侵入式Boost序列化C ++的私有数据成员

这是Tanner在在魔盒上直播 >

  • a.h

    #pragma once
    
    class A {
    private:
        int elemA;
    
    public:
        A(int elem = 0) : elemA(elem) {};
        virtual ~A() = default;
    
        int getElemA() const { return elemA; }
        void setElemA(int elem) { elemA = elem; }
    };
    

  • b.h

    #pragma once
    #include "a.h"
    
    class B : public A {
    private:
        int elemB;
    
    public:
        B(int elem = 0) : A(42), elemB(elem) {};
    
        int getElemB() const { return elemB; }
        void setElemB(int elem) { elemB = elem; }
    };
    

  • main.cpp

    #include <string>
    #include <sstream>
    #include <iostream>
    
    #include <boost/archive/text_oarchive.hpp>
    #include <boost/archive/text_iarchive.hpp>
    #include <boost/serialization/base_object.hpp>
    #include <boost/serialization/export.hpp>
    #include "b.h"
    
    BOOST_CLASS_EXPORT(A)
    BOOST_CLASS_EXPORT(B)
    
    namespace privates {
    
        template <typename Key, typename Key::type PointerToMember> struct store {
            friend typename Key::type get(Key) { return PointerToMember; }
        };
    
        struct elemA {
            typedef int A::*type;
            friend type get(elemA); // ADL-enable
        };
    
        struct elemB {
            typedef int B::*type;
            friend type get(elemB); // ADL-enable
        };
    
        template struct store<elemA, &A::elemA>;
        template struct store<elemB, &B::elemB>;
    
    } // namespace privates
    
    auto& getElemA(A& instance) { return instance.*(get(privates::elemA())); }
    auto& getElemB(B& instance) { return instance.*(get(privates::elemB())); }
    
    namespace boost {
        namespace serialization {
            template<class Archive>
            void serialize(Archive & ar, A& v, unsigned) { ar & getElemA(v); }
    
            template<class Archive>
            void serialize(Archive & ar, B& v, unsigned) { ar & base_object<A>(v) & getElemB(v); }
        }
    }
    
    template <typename T> void run_tests() {
        std::stringstream ss;
        {
            A *obj= new T(747);
            boost::archive::text_oarchive oa(ss);
            oa << obj;
            delete obj;
        }
    
        std::cout << ss.str() << "\n";
    
        {
            A *obj = nullptr;
            boost::archive::text_iarchive ia(ss);
            ia >> obj;
            delete obj;
        }
    }
    
    int main()
    {
        run_tests<A>();
        run_tests<B>();
    }
    

请注意,它简化了几件事,并且在没有异常的情况下至少消除了内存泄漏.

输出 在魔盒上直播

22 serialization::archive 15 0 1 0
0 747

22 serialization::archive 15 1 1 B 1 0
0 1 0
1 42 747

I try to serialize a class, say B (in file b.h), which is derived from another one, say A (in file a.h). Both classes have private members and I want to serialize both with the boost serialization library non-intrusively. The serialization/deserialization of A does work so far. For the same for the derived class one would use

ar & boost::serialization::base_object<base_class>(*this);

when the intrusive method is used, but where to put it in the non-intrusive case (save/load/serialize or all three?)? And what object has to been used in place of the this pointer?

In the productive code I have derived class a bit more complicated than B. There I got a compiler error which I wasn't able to reproduce in this small example. The compiler message (MSVC 2015, C2665, translated in English):

'boost::serialization::save' : none of the number1 overloads can convert parameter number2 from type 'type'

The Error in German:

Fehler C2665 "boost::serialization::save": Durch keine der 3 Überladungen konnten alle Argumenttypen konvertiert werden. CalorCLI c:\boost_1_61_0\boost\serialization\split_free.hpp 45

Could anyone help?

The Code of a.h :

#pragma once

class A {
private:
    int elemA;

public:
    A() = default;
    A(int elem) : elemA(elem) {};
    virtual ~A() = default;

    int getElemA() const { return elemA; }
    void setElemA(int elem) { 
        elemA = elem; 
    }

};

The code of b.h :

#pragma once
#include "a.h"

class B : public A {
private:
    int elemB;

public:
    B() = default;
    B(int elem) : elemB(elem) {};
    virtual ~B() = default;

    int getElemB() const { return elemB; }
    void setElemB(int elem) { elemB = elem; }

};

The Code of the main program:

// TestSerialization.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include <string>
#include <fstream>
#include <iostream>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "b.h"
#include "stdafx.h"

namespace boost {
    namespace serialization {

        template<class Archive>
        void save(Archive & ar, const A & pA, const unsigned int version)
        {
            ar & pA.getElemA();
        }

        template<class Archive>
        void load(Archive & ar, A & pA, const unsigned int version)
        {
            int n;
            ar & n; 
            pA.setElemA(n); 
        }

        template<class Archive>
        void serialize(Archive & ar, A & pA, const unsigned int version)
        {
            boost::serialization::split_free(ar, pA, version);
        }

        template<class Archive>
        void save(Archive & ar, const B & pB, const unsigned int version)
        {
            ar & pB.getElemB();
        }

        template<class Archive>
        void load(Archive & ar, B & pB, const unsigned int version)
        {
            int n;
            ar & n;
            pB.setElemB(n);
        }

        template<class Archive>
        void serialize(Archive & ar, B & pB, const unsigned int version)
        {
            boost::serialization::split_free(ar, pB, version);
        }
    }
}

int main()
{
    A *objA= new A(747);
    {
        std::ofstream ofs("SavedA");
        boost::archive::text_oarchive oa(ofs);
        oa << objA;
    }

    {
        A *objA1 = new A();
        std::ifstream ifs("SavedA");
        boost::archive::text_iarchive ia(ifs);
        ia >> objA1;
    }

    B *objB = new B(747);
    {
        std::ofstream ofs("SavedB");
        boost::archive::text_oarchive oa(ofs);
        oa << objB;
    }

    {
        B *objB1 = new B();
        std::ifstream ifs("SavedB");
        boost::archive::text_iarchive ia(ifs);
        ia >> objB1;
    }

    return 0;
}

First, a fair warning about Quasi-Classes (PDF). They are the enemy of encapsulation and confuse OOP.

Next, let me answer two of your questions real quick and proceed to show my take on this:

  1. Q. where to put it in the non-intrusive case (save/load/serialize or all three?)?

    Either in serialize OR in both save and load (if you have split implementations)

  2. Q. what object has to been used in place of the this pointer?

    The same object. If you do member-function serialize this points to the same object as gets passed the free function as the second argument. Just use that object.

My Take

Now, let me refer to my answer to Get private data members for non intrusive boost serialization C++

Here's a demonstration of the idea Tanner suggested in his comment

Live On WandBox

  • a.h

    #pragma once
    
    class A {
    private:
        int elemA;
    
    public:
        A(int elem = 0) : elemA(elem) {};
        virtual ~A() = default;
    
        int getElemA() const { return elemA; }
        void setElemA(int elem) { elemA = elem; }
    };
    

  • b.h

    #pragma once
    #include "a.h"
    
    class B : public A {
    private:
        int elemB;
    
    public:
        B(int elem = 0) : A(42), elemB(elem) {};
    
        int getElemB() const { return elemB; }
        void setElemB(int elem) { elemB = elem; }
    };
    

  • main.cpp

    #include <string>
    #include <sstream>
    #include <iostream>
    
    #include <boost/archive/text_oarchive.hpp>
    #include <boost/archive/text_iarchive.hpp>
    #include <boost/serialization/base_object.hpp>
    #include <boost/serialization/export.hpp>
    #include "b.h"
    
    BOOST_CLASS_EXPORT(A)
    BOOST_CLASS_EXPORT(B)
    
    namespace privates {
    
        template <typename Key, typename Key::type PointerToMember> struct store {
            friend typename Key::type get(Key) { return PointerToMember; }
        };
    
        struct elemA {
            typedef int A::*type;
            friend type get(elemA); // ADL-enable
        };
    
        struct elemB {
            typedef int B::*type;
            friend type get(elemB); // ADL-enable
        };
    
        template struct store<elemA, &A::elemA>;
        template struct store<elemB, &B::elemB>;
    
    } // namespace privates
    
    auto& getElemA(A& instance) { return instance.*(get(privates::elemA())); }
    auto& getElemB(B& instance) { return instance.*(get(privates::elemB())); }
    
    namespace boost {
        namespace serialization {
            template<class Archive>
            void serialize(Archive & ar, A& v, unsigned) { ar & getElemA(v); }
    
            template<class Archive>
            void serialize(Archive & ar, B& v, unsigned) { ar & base_object<A>(v) & getElemB(v); }
        }
    }
    
    template <typename T> void run_tests() {
        std::stringstream ss;
        {
            A *obj= new T(747);
            boost::archive::text_oarchive oa(ss);
            oa << obj;
            delete obj;
        }
    
        std::cout << ss.str() << "\n";
    
        {
            A *obj = nullptr;
            boost::archive::text_iarchive ia(ss);
            ia >> obj;
            delete obj;
        }
    }
    
    int main()
    {
        run_tests<A>();
        run_tests<B>();
    }
    

Note it simplifies a few things and at least removed memory-leaks when there were no exceptions.

Output Live On WandBox

22 serialization::archive 15 0 1 0
0 747

22 serialization::archive 15 1 1 B 1 0
0 1 0
1 42 747