c++ - boost:scoped_ptr with legacy C functions that takes char* as input type? -
i new boost library , started exploring @ work new project. want understand how scoped_ptr boost works? till using raw pointers in our codes , propsed use smartpointers make memory management easy. our programming not pure c++ language integrated application language. example trying understand how can initialize scoped_ptr null , pass raw pointer application api. consider code below
this api application toolkit takes arguments this
int some_api_func(int obj, const char* prop, char** cvalue);
i cannot change api because not published.
now parameter cvalue want use smart pointer memory management automated since api dynamically allocates memory , assigns value , returns.
we tried scoped_ptr declaring this
boost::scoped_ptr<char*> pcvalue(new char*());
and used in api like
some_api_func(obj, prop,&*cvalue);
my question if cvalue allocated malloc internally inside api happens since scoped_ptr using delete? delete clean memory properly? how validate memory cleaned properly?
you should use smart pointer customizable deleter.
e.g. if need free pointer free
instead of delete
(the default deleter), try:
struct free_deleter { template <typename t> void operator()(t* p) const { ::free(p); } }; template <typename t> using malloc_ptr = std::unique_ptr<t, free_deleter>;
now can indeed assign malloced pointers , fine:
std::unique_ptr<char[]> a(new char[100]); // ok, uses `delete[]` std::unique_ptr<mytype> b(new mytype("param")); // ok, uses `delete` malloc_ptr<char> legacy_buf(static_cast<char*>(::malloc(100))); //ok, uses `::free`
Comments
Post a Comment