Lets say I have heap allocated A*, which I want to pass as argument to boost::bind.
boost::bind is saved for later processing in some STL like container of boost::functions‘s.
I want to ensure A* will be destroyed at destruction of the STL container.
To demostrate:
A* pA = new A();
// some time later
container.push_back(boost::bind(&SomeClass::HandleA, this, pA);
// some time later
container is destroyed => pA is destroyed too
How can it be done?
EDIT
Maybe what I want is not that realistic.
I have raw pointer and function which receives the raw pointer. The call is delayed by means of boost::bind. At this point I want automatic memory management in case boost::bind want executed. I’m lazy, so I want to use “ready” smart-pointer solution.
std::auto_ptr looks like a good candidate, however …
auto_ptr<A> pAutoA(pA);
container.push_back(boost::bind(&SomeClass::HandleA, this, pAutoA);
doesn’t compile (see here)
auto_ptr<A> pAutoA(pA);
container.push_back(boost::bind(&SomeClass::HandleA, this, boost::ref(pAutoA));
pAutoA is destroyed, deleting underlying pA.
EDIT 02
In the mentioned container I will need to store misc “callbacks” with different arguments. Some of them are raw pointers to object. Since the code is old, I not always can change it.
Writing own wrapper for storing callbacks in container is last resort (while maybe the only one), hence bounty.
The idea of @pmjordan was already going in the right direction. You replied that you can’t use
shared_ptr, because you can’t take ownership back from it once constructed. But that is not entirely correct: withshared_ptr‘s custom deleter mechanism, you can. This is how:Assume these toy defintions for your
Aandf(A*):Write a deleter that can be “switched off”:
Then you can write a
take()function that takes ownership of theshared_ptrpayload again:(this will leave the payload in the remaining
shared_ptrinstances, but for your case, that’s ok, and theassert()s cover the cases when it’s not).Now you can manually wrap
f(A*)like this:And finally, test the two scenarios:
Executing the test program with a
1argument will printand without (or any other argument), it will print
You can extend the test harness to put
funcinto a container first, but it’ll still be safe. The only thing that isn’t safe in the case is calling thefunccopies more than once (but then you’ll trigger the second assertion intake()).EDIT: Note that this mechanism isn’t thread-safe. To make it thread-safe, you need to supply
opt_deletewith a mutex to synchroniseoperator()withtake().