gpt4 book ai didi

c++ - 序列化异构映射

转载 作者:行者123 更新时间:2023-11-30 04:24:52 25 4
gpt4 key购买 nike

我必须将 map 序列化到文件。首先,我将映射放入字节缓冲区,然后将字节缓冲区写入文件。在加载方法中,首先将整个文件读入字节缓冲区,然后从字节缓冲区填充 map 。目前我有这段代码(没有文件处理):

保存方法:

map<int, BaseClass*> myMap;
map<int, BaseClass*>::iterator it;
ByteBuffer bb;

bb.putUInt(myMap.size());
for (it = myMap.begin(); it!= myMap.end(); it++){
bb.putUInt(it->first);
it->second->save(bb); // the save method put the static type first, then the data
}

加载方式

...// get the map size from bb
for (int i=0; i<size; i++){
int key = bb.getUInt() // in the real code there isn't signed/unsigned mismatch
BaseClass* value = MyFactory.create(bb) // detailed later
myMap.insert(key,value);
}

MyFactory.create:

BaseClass* MyFactory::create( ByteBuffer& bb){
TypeEnum type = static_cast<TypeEnum>(bb.getUInt());
BaseClass* value;

switch (type){
case DerivedClass1:
value = new DerivedClass1()
break;

case DerivedClass2:
value = new DerivedClass2()
break;

// etc...
}

value->load(bb);
return value;
}

有了这个解决方案,我有一个大枚举 TypeEnum,一个长开关,并且对于来自基类的每个新派生类,我都必须增加它们。有没有更好的方法来做到这一点?

最佳答案

我认为你的做法是正确的。但是,您可能需要考虑以下改进:

在 factory::create 中使用智能指针。因为现在它不是异常安全的:

    std::auto_ptr<BaseClass> MyFactory::create(ByteBuffer& bb)
{
TypeEnum type = static_cast<TypeEnum>(bb.getUInt());
std::auto_ptr < BaseClass > value;
switch (type)
{
case DerivedClass1:
value.reset(new DerivedClass1());
break;
case DerivedClass2:
value.reset(new DerivedClass2());
break;
}
value->load(bb);
return value;
}

这样,如果加载失败,您就不会发生内存泄漏。

关于c++ - 序列化异构映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12473627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com