gpt4 book ai didi

c++ - boost::shared_ptr 不序列化数据并给出错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:20 24 4
gpt4 key购买 nike

我在使用 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因此它给出了错误:

它给出错误:error C4308: negative integral constant converted to unsigned type

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

最佳答案

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

@user3382670 making the destructor virtual enabled RTTI for your class. This means that typeid(variable) will return the proper runtime type (most derived class) insetad of the statically known type with pointers and references. – sehe Mar 22 at 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;
}

关于c++ - boost::shared_ptr<Type> 不序列化数据并给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22659216/

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