提升序列化多态类 [英] boost serialize polymorphic class
问题描述
在下面的示例中,我尝试学习一些新概念.
With the following example I attempting to learn a few new to me concepts.
- 抽象
- 多态类
- 工厂编程.
- 提升序列化
我仍在努力弄清指针行为的细微差别.
The nuances of how pointers behave are still something I am working to figure out.
这是我编写的一个小程序,向您显示我正在努力理解的问题.
当我反序列化下面的多态对象时,只能得到从默认构造函数创建的对象.
TodoFactory :: retrieveATodo不会从序列化数据中重新创建对象.通过该功能中未序列化命令"的输出显示.
Here is a small program that I have written to show you the issue I am struggling to understand.
When I unserialize the polymorphic object below I only get an object created from the default constructor.
TodoFactory::retrieveATodo is not recreating the object from the serialized data. This is displayed by the output of "unserialzed command" in that function.
这是完整的程序:
#include <string>
#include <bitset>
#include <boost/serialization/string.hpp>
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
//abstract class
class aTodo{
private:
friend class boost::serialization::access;
protected:
const char _initType;
public:
aTodo():_initType(0x00){};
aTodo(const char type):_initType(type){};
std::string oarchive(){
std::ostringstream archive_stream;
{
boost::archive::text_oarchive archive(archive_stream);
archive << *this;
}
archive_stream.flush();
std::string outbound_data=archive_stream.str();
std::string foutbound_data;
foutbound_data=_initType;
foutbound_data+=outbound_data;
std::cout << "length: " << foutbound_data.length() << std::endl;
return foutbound_data;
}
virtual void Do()=0;
virtual ~aTodo(){};
template<class Archive>
void serialize(Archive & ar, unsigned int version){
ar & _initType;
};
char getInitType(){return _initType;};
};
// include headers that implement a archive in simple text format
class todoExec:public aTodo{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(
Archive& ar,
unsigned int version
)
{
std::cout << "serialize todoexec" << std::endl;
//base
boost::serialization::base_object<aTodo>(*this);
//derived
ar & _command;
}
std::string _command;
protected:
public:
static const char _TYPE=0x01;
todoExec():aTodo(_TYPE){};
todoExec(std::string command):aTodo(_TYPE){_command=command;};
void Do(){std::cout << "foo" << std::endl;};
virtual ~todoExec(){};
std::string getCommand(){return _command;};
};
class todoFactory{
private:
protected:
public:
std::unique_ptr<aTodo> retrieveAtodo(const std::string & total){
std::cout << "here" << std::endl;
char type=total.at(0);
std::cout << "bitset: " << std::bitset<8>(type) << std::endl;
std::string remainder=total.substr(1);
if(type==0x01){
std::cout << "remainder in retrieve: " << remainder << std::endl;
std::unique_ptr<todoExec> tmp(new todoExec());
std::stringstream archive_stream(remainder);
std::cout << "stream remainder: " << archive_stream.str() << std::endl;
{
boost::archive::text_iarchive archive(archive_stream);
archive >> *tmp;
}
std::cout << "unserialized type: " << std::bitset<8>(tmp->getInitType()) << std::endl;
std::cout << "unserialized command: " << tmp->getCommand() << std::endl;
return std::move(tmp);
}
};
std::unique_ptr<aTodo> createAtodo(char type,std::string command){
if(type==0x01){
std::unique_ptr<todoExec> tmp(new todoExec(command));
return std::move(tmp);
}
};
};
int main(){
char mtype=0x01;
std::string dataToSend = "ls -al /home/ajonen";
std::unique_ptr<todoFactory> tmpTodoFactory; //create factory
std::unique_ptr<aTodo> anExecTodo=tmpTodoFactory->createAtodo(mtype,dataToSend); //create ExecTodo from factory
if(auto* m = dynamic_cast<todoExec*>(anExecTodo.get()))
std::cout << "command to serialize: " << m->getCommand() << std::endl;
//archive
std::string remainder = anExecTodo->oarchive();
//now read in results that are sent back
std::unique_ptr<aTodo> theResult;
theResult=tmpTodoFactory->retrieveAtodo(remainder);
std::cout << "resultant type: " << std::bitset<8>(theResult->getInitType()) <<std::endl;
if(auto* d = dynamic_cast<todoExec*>(theResult.get()))
std::cout << "resultant Command: " << d->getCommand() <<std::endl;
return 0;
}
这是程序输出:
command to serialize: ls -al /home/ajonen
length: 36
here
bitset: 00000001
remainder in retrieve: 22 serialization::archive 12 0 0 1
stream remainder: 22 serialization::archive 12 0 0 1
serialize todoexec
unserialized type: 00000001
unserialized command:
resultant type: 00000001
resultant Command:
我还发现,只对基类aTodo调用了serialize方法.我将需要找到一种方法来使其虚拟化,但这是一种模板功能.那是第一问题.
I also found out that the serialize method is only being called for the base class aTodo. I am going to need to find a way to make that virtual, but it is a template function. That is problem number one.
推荐答案
您的程序具有未定义的行为,因为所有的工厂功能都缺少回报.
Your program has Undefined Behaviour because all of the factory functions have missing returns.
接下来,在类层次结构中使用类型代码是设计气味.
Next up, using a type code in a class hierarchy is a Design Smell.
具体提示:
- 序列化与反序列化相同的类型
- 让Boost序列化处理多态性(否则,为什么要使用多态性,或者为什么要使用Boost序列化?).当您将(智能)指向序列的指针序列化时,Boost会处理它.
- 注册您的课程(BOOST_CLASS_EXPORT).您已包含标头,但未使用它.
- 工厂似乎没有原因.考虑删除它
- serialize the same type as you deserialize
- let Boost Serialization handle the polymorphism (otherwise, why do you use polymorphism, or why do you use Boost Serialization?). Boost handles it when you serialize (smart) pointers to base.
- register your classes (BOOST_CLASS_EXPORT). You had included the header but didn't use it.
- There doesn't seem to be a reason for the factory. Consider dropping it
通常,除去木屑.当您的代码过于嘈杂时,很难想到.这是我的清理版本:
In general, remove cruft. it's hard to think when your code is too noisy. Here's my cleaned up version:
这也使用Boost将流传输到字符串,而无需不必要的复制.
This also uses Boost for streaming to string without unnecessary copying.
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
namespace Todo
{
struct BaseTodo {
using Ptr = std::unique_ptr<BaseTodo>;
virtual ~BaseTodo() = default;
virtual void Do() = 0;
virtual unsigned getInitType() { return 0x00; };
private:
friend class boost::serialization::access;
template <class Ar> void serialize(Ar &, unsigned) {}
};
class Exec : public BaseTodo {
public:
Exec(std::string const &command = "") : _command(command){};
virtual unsigned getInitType() { return 0x01; };
virtual void Do() { std::cout << "foo: " << getCommand() << std::endl; };
std::string getCommand() const { return _command; };
private:
friend class boost::serialization::access;
template <class Archive> void serialize(Archive &ar, unsigned) {
boost::serialization::base_object<BaseTodo>(*this);
ar &_command;
}
std::string _command;
};
}
//BOOST_CLASS_EXPORT(BaseTodo)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(Todo::BaseTodo)
BOOST_CLASS_EXPORT(Todo::Exec)
namespace Todo
{
class Factory {
Factory() = default;
public:
using Ptr = BaseTodo::Ptr;
using FactoryPtr = std::shared_ptr<Factory>;
static FactoryPtr create() { return FactoryPtr(new Factory); }
static std::string save(Ptr todo) {
std::string out;
{
namespace io = boost::iostreams;
io::stream<io::back_insert_device<std::string> > os(out);
boost::archive::text_oarchive archive(os);
archive << todo;
}
return out;
}
static Ptr load(std::string const &s) {
Ptr p;
{
namespace io = boost::iostreams;
io::stream<io::array_source> is(io::array_source{ s.data(), s.size() });
boost::archive::text_iarchive archive(is);
archive >> p;
}
return std::move(p);
}
Ptr createExec(std::string command) { return BaseTodo::Ptr(new Exec(command)); }
};
}
int main() {
auto factory = Todo::Factory::create();
// ROUNDTRIP save,load
auto todo = factory->load(
factory->save(
factory->createExec("ls -al /home/ajonen")
)
);
std::cout << "Type: " << std::hex << std::showbase << todo->getInitType() << std::endl;
todo->Do();
}
这篇关于提升序列化多态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!