Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost serialize and std::shared_ptr

Tags:

c++

boost

I Have a object which the following field :

boost::unordered_map<std::string, std::shared_ptr<Foo> > m_liste_;

I would like to serialize it, but it seems std::shared_ptr can't be serialized in a simple manner

anyone have a solution ?

like image 872
Guillaume Paris Avatar asked Mar 30 '12 13:03

Guillaume Paris


People also ask

What is boost :: shared_ptr?

shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.

Why would you choose shared_ptr instead of Unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

What does shared_ptr get () do?

A shared_ptr can share ownership of an object while storing a pointer to another object. This feature can be used to point to member objects while owning the object they belong to. The stored pointer is the one accessed by get(), the dereference and the comparison operators.

When should you use shared_ptr?

An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of shared_ptr have been deleted. So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object.


1 Answers

I suspect you are missing an include,

#include <boost/serialization/shared_ptr.hpp>

link, at the bottom

Also, the example makes it look like aliasing and cycles are taken care of by default.

_Of course, having cycles will lead to potential memory leaks with shared_ptr that have nothing to do with serialization, and you'll still have to heed those (by avoiding cycles or judicious use of weak_ptr)_

See also:

  • Template serialization - shared_ptr
  • shared_ptrRevisited
like image 163
sehe Avatar answered Oct 03 '22 03:10

sehe