I am using Msgpack-c. One thing that is not clear to me, is how to correctly handle memory when using this library. The quickstart examples declare everything locally and I presume rely on destructors being called when the application ends, but I cannot rely on the same.
Take the following:
msgpack::unpacked msgunpacked;
msgpack::unpack(&msgunpacked, msgdata, msglength);
T params = msgunpacked.get().as<T>();
return params ;
When is it safe to delete msgdata? After unpack()? After the conversion to T?
When is it safe to delete msgunpacked? After get()?
Do I need to delete or free params? And do I need to destroy members like msgpack::type::raw_ref explicitly?
When you use
msgpack::unpack()function, the default unpacking behavior is copy. So you can destroymsgdataaftermsgpack::unpack()is called.See memory management
You can customize the behavior of copy. When you pass
unpack_reference_funchandler tomsgpack::unpack(), and when the handler returns true,msgpack::unpackedmight refer tomsgdata. You can check the reference status viareferencedparameter. If thereferenceparameter is set to true, themsgpack::unpackedrefers tomsgdata.Strictly speaking,
msgpack::unpackeddoesn't refer tomsgdatadirectly,msgpack::objectthat is held bymsgpack::unpackedrefers tomsgdata.See accessing unpacked data
get()is the member function for gettingmsgpack::object. Themsgpack::objectis located onmsgpack::zone, a kind of memory pool. Andmsgpack::unpackedcontainsstd::unique_ptr<msgpack::zone>. That means you need to keep the lifetime ofmsgunpackedduring you access themsgpack::objectthat is gotten byget(). If you convert to T frommsgpack::object, and the T doesn't refer tomsgpack::object, and you don't accessmsgpack::objectany more, then you can destroymsgunpacked. I said that the T doesn't refer tomsgpack::object. It depends on the type of T. Most of the types do not refer tomsgpack::object.msgpack::type::raw_ref,boost::string_ref, andmsgpack::type::variant_refrefer tomsgpack::object.If you convert to those types, you need to keep the lifetime of
msgpack::object.See conversion , adaptor , variant_ref
No. T is located on the stack, you don't need to free it. If T contains the data on the heap like as
std::vector<sometype>, the data should be freed by the destructor of the T.No, you don't need to free
msgpack::type::raw_ref. It is just a reference type object. The memory that is referred bymsgpack::type::raw_refis freed whenmsgunpackedis freed.