Reputation: 5675
I need to map a delete ptrAddr;
to a boost::function0
but i have some troubles doing that for delete. free works just fine. The issue appears to be std::ptr_fun(operator delete)
but i can't figure how to make this work without writing a helper functor.
boost::function0<void> Function;
Function = boost::bind(std::ptr_fun(free), (void*)malloc_string); //this works
Function = boost::bind(std::ptr_fun(operator delete), (void*)new_string); //doesn't work
Function(); //call function
Upvotes: 3
Views: 2002
Reputation: 129764
You can use delete_ptr
from Boost.Lambda:
boost::bind(boost::delete_ptr(), new_string);
In C++11, you can use std::default_delete<T>
:
std::bind(std::default_delete<decltype(new_string)>(), new_string);
Or just a lambda:
[new_string]() { delete new_string; }
Upvotes: 12
Reputation: 476970
delete p;
is not a function call; it's an expression. What you want doesn't make sense.
There does exist a free function ::operator delete()
, but that doesn't do what you think.
Look at the implementation of any standard library container (keyword: allocator), or perhaps std::unique_ptr
, to see how one handles customizable object deletion.
The typical construction/destruction sequence broken down into pieces looks like this:
void * addr = ::operator new(sizeof(T)); // allocation
T * p = ::new (addr) T; // construction
p->~T(); // destruction
::operator delete(addr); // deallocation
The first to steps are morally equivalent to the expression T * p = new T;
, while the last to correspond to delete p;
. There is no way to call a constructor other than through a new
expression, though; and you mustn't forget to invoke the destructor one way or another.
Upvotes: 4