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 destroymsgdata
aftermsgpack::unpack()
is called.See memory management
You can customize the behavior of copy. When you pass
unpack_reference_func
handler tomsgpack::unpack()
, and when the handler returns true,msgpack::unpacked
might refer tomsgdata
. You can check the reference status viareferenced
parameter. If thereference
parameter is set to true, themsgpack::unpacked
refers tomsgdata
.Strictly speaking,
msgpack::unpacked
doesn't refer tomsgdata
directly,msgpack::object
that is held bymsgpack::unpacked
refers tomsgdata
.See accessing unpacked data
get()
is the member function for gettingmsgpack::object
. Themsgpack::object
is located onmsgpack::zone
, a kind of memory pool. Andmsgpack::unpacked
containsstd::unique_ptr<msgpack::zone>
. That means you need to keep the lifetime ofmsgunpacked
during you access themsgpack::object
that is gotten byget()
. If you convert to T frommsgpack::object
, and the T doesn't refer tomsgpack::object
, and you don't accessmsgpack::object
any 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_ref
refer 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_ref
is freed whenmsgunpacked
is freed.