【问题标题】:Boost deserialization of contained object fails when performed from a constructor, but succeeds otherwise从构造函数执行时,包含对象的 Boost 反序列化失败,否则成功
【发布时间】:2009-10-28 21:18:28
【问题描述】:

从构造函数执行包含对象的Boost反序列化失败,否则成功。

例如:

ContainingClass::ContainingClass() {
    pNA = new objectArray*[NUMBER]; // allocates ptrs
    // ...
    pNA[ii] = new objectArray(SIZE);// allocates object array, and object array
                                    // has a std::map "PatternsMap"
    // ...

    pNA[ii]->load(pNA[ii], "../release/NA Data/NAData_a description_NA0"); //fails
    pNA[ii]->PatternsMap.size(); //size = 0
}

如果我在构造函数退出后调用以下代码行,那么一切都很好:

pNA[ii]->load(pNA[ii], "../release/NA Data/NAData_a description_NA0"); //succeeds
pNA[ii]->PatternsMap.size();//size > 0

有什么想法吗?请注意,在构造函数示例中,我验证了 objectArray 是首先构造的。

【问题讨论】:

    标签: c++ serialization boost constructor


    【解决方案1】:

    更喜欢使用 std::vector 或 Boost.Array 而不是普通数组,您会遇到更少的内存问题……而且它们实际上默认构造了它们持有的对象,因此可以节省一些代码行。

    我猜loadobjectArray 的一个方法,不知道你为什么这么称呼它:

    pNA[ii]->load(pNA[ii], "../release/NA Data/NAData_a description_NA0");
    

    我的意思是,当使用一个方法时,你已经有一个隐式参数 (this) 来引用该对象,实际上不需要传递它两次(一次是隐式的,一次是显式的)。

    当然,如果我们可以看看load 方法,那将会很有帮助。诊断问题类型非常困难:

    我的方法foo失败了,你知道为什么吗?

    你越精确,就越有可能有人真正准确地指出你的问题。

    【讨论】:

      【解决方案2】:

      致:Stjepan Rajko: ContainingClass 是在运行时动态创建的。

      致马蒂厄 M: 看来 Boost 作者可能陷入了“全局初始化惨败”。

      根据关于 std::vector 的评论,我使用普通数组,因为代码是高度并行的,我期待将其中的一部分移至 NVidia 的 CUDA。 CUDA 目前不支持 C++,只支持 C。此外,(虽然不是一个因素)我对使用动态数组并在之后显式释放内存感到很自在……加上性能是重中之重。我在我认为合适的地方使用了 std::vector 和 smart/auto ptrs。

      根据关于隐含 this 的评论,是的,您可能是正确的...我不确定当我明确表示时我在想什么。这是 objectArray 类中的序列化代码:

      template[class Archive]//注意这个帖子的括号必须改变

      void serialize(Archive & ar, const unsigned int 版本) {

      // 只为较新的档案保存/加载 A_name

      //如果(版本> 0)

      // ar & A_name;

      ar & PatternsMap;

      }

      void store(objectArray s, const char 文件名) {

      // create and open a character archive for output
      std::ofstream ofs(filename);
      boost::archive::text_oarchive oa(ofs);
      // write class instance to archive
      oa << s;
      // archive and stream closed when destructors are called
      

      }

      void load(objectArray s, const char 文件名) {

      std::ifstream ifs(filename);
      boost::archive::text_iarchive ia(ifs);
      // read class state from archive
      ia >> s;
      // archive and stream closed when destructors are called
      

      }

      【讨论】:

      • 你知道,std::vector 保证将其内容存储在连续的内存中,就像一个数组,所以你可以将一个向量传递给一个期望指针加上大小的 C 函数,如下所示: f( &vec[0], vec.size())
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2011-12-02
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多