【问题标题】:boost::shared_ptr<Type> does not serialize the data and gives errorboost::shared_ptr<Type> 不序列化数据并给出错误
【发布时间】:2014-03-26 11:13:31
【问题描述】:

我在使用 boost 序列化共享指针时再次遇到问题,下面是代码:

//内容.hpp文件

#include <boost/serialization/string.hpp>
#include <boost\serialization\shared_ptr.hpp>
#include <boost/serialization/list.hpp>


struct Content
    {

        std::string type;
    boost::shared_ptr<Content> mycontent;  // mycontent is of type Content


    private:
        friend class boost::serialization::access;
        template<class Archive>
        void serialize(Archive &ar, const unsigned int version)
        {
            ar & id;
            ar & name;
        ar & mycontent;
        }   

    public:
        Content(void);
        Content(const parameter_strings & parms);

        ~Content(void);
    };

// 内容.cpp 文件

Content::Content(void)
{
}

Content::~Content(void)
{
}

Content::Content(const parameter_strings & parms)
{
   // implementation part
}

如果我注释行“-- boost::shared_ptr mycontent;--”它编译没有错误,但我需要使用 shared_ptr,因此它给出错误:

它给出错误:错误 C4308:负整数常量转换为无符号类型

我也包含了所有必需的头文件,但问题仍然存在。

【问题讨论】:

标签: c++ visual-studio-2012 serialization boost


【解决方案1】:

我已经在这里回答了这个in the comments

@user3382670 使析构函数为您的课程虚拟启用 RTTI。这意味着 typeid(variable) 将返回带有指针和引用的静态已知类型的正确运行时类型(大多数派生类)插入。 – 3 月 22 日 1:01

此外,由于您不需要多态性,因此首先应该没有这样的问题:请参阅 Live On Coliru

#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/shared_ptr.hpp>

struct Content
{
    std::string id, name;
    boost::shared_ptr<Content> mycontent;

  private:
    friend class boost::serialization::access;
    template<class Archive>
        void serialize(Archive &ar, const unsigned int /*version*/)
        {
            ar & id;
            ar & name;
            ar & mycontent;
        }   

  public:
    Content() {}
    typedef int parameter_strings;
    Content(const parameter_strings & parms) { }

    ~Content() {}
};

int main()
{
    boost::archive::text_oarchive ao(std::cout);

    Content x;
    ao << x;
}

【讨论】:

  • 我尝试了上面的代码..但仍然存在同样的问题..我应该让我的析构函数非虚拟吗??
猜你喜欢
  • 1970-01-01
  • 2012-10-05
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2016-02-28
相关资源
最近更新 更多