boost::serialization 如何与 C++11 中的 std::shared_ptr 一起使用?

2023-07-20C/C++开发问题
0

本文介绍了boost::serialization 如何与 C++11 中的 std::shared_ptr 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道有一个Boost模块序列化的boost::shared_ptr,但我找不到任何东西对于 std::shared_ptr.

另外,我不知道如何轻松实现它.恐怕下面的代码

Also, I don't know how to implement it easily. I'm afraid that the following code

namespace boost{namespace serialization{
template<class Archive, class T>
inline void serialize(Archive & ar, std::shared_ptr<T> &t, const unsigned int version)
{
  if(Archive::is_loading::value) {T*r;ar>>r;t=r;}
  else {ar<<t.get();}
}
}}//namespaces

不起作用.事实上,如果某个对象被多次引用,它将在第一次运行 ar>>r 时加载,然后只复制一个指针.然而,我们会创建多个指向它的 shared_ptr 对象,因此会多次破坏它.

doesn't work. Indeed, if some object was referred multiple times, it would be loaded with first run of ar>>r, and after that just a pointer will be copied. However we would create multiple shared_ptr objects pointing to it, and therefore would destruct it more than one time.

对此有什么想法吗?

关于我正在使用的系统的一些技术细节:

Some technical details about the system I'm using:

  • 操作系统:Ubuntu 11.10 (x64)
  • 编译器:g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
  • boost 版本:1.46.1(使用 sudo apt-get install libboost-dev 安装)

推荐答案

从 Boost 1.56 开始,序列化库有 对 std::shared_ptr 的内置支持.如果您可以使用该库的更新版本,则无需实现自己的序列化辅助函数.

As of Boost 1.56, the serialization library has built-in support for std::shared_ptr. You do not need to implement your own serialization helper functions if you can use a more recent version of the library.

这篇关于boost::serialization 如何与 C++11 中的 std::shared_ptr 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6