Reputation: 11
I am new to boost library and started exploring it now at my work for a new project. I want to understand how the scoped_ptr from BOOST works? Till now we are using raw pointers in all our codes and I propsed to use SmartPointers to make the memory management easy. Our programming is not a pure C++ language but its integrated application language. For example we are trying to understand how we can initialize a scoped_ptr to NULL and pass the raw pointer to the application API. Consider the code below
This is the API from the application toolkit which takes arguments like this
int SOME_API_FUNC(int obj, const char* prop, char** cValue);
I cannot change the API because it is not published.
Now the parameter cValue is where we want to use Smart Pointer so that the memory management is automated since the API dynamically allocates some memory for it and assigns a value and returns.
We tried with scoped_ptr declaring it like this
boost::scoped_ptr<char*> pcValue(new char*());
and used in the API like
SOME_API_FUNC(obj, prop,&*cValue);
My question is if this cValue is allocated with malloc internally inside the API then what happens since the scoped_ptr is using delete? Will delete clean up the memory properly? How to validate that the memory is cleaned up properly?
Upvotes: 0
Views: 112
Reputation: 393084
You should use a smart pointer with a customizable deleter.
E.g. if you need to free that pointer with 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 you can indeed assign malloced pointers and be 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`
Upvotes: 1