RE: [Boost-Users] Re: Why scoped_ptr dost provide custom dealloca tion?
From: Peter Dimov [mailto:pdimov@mmltd.net] [snip] (An example of a convincing case: "In my project I have encountered the following situation: <description with real(istic sounding) identifiers> and I believe that scoped_ptr<X, D> would be a perfect fit." Some non-examples: "Someone might find it useful." "Wouldn't it be cool if...")
In my project I have encountered the following situation: A lot of the code needs to handle (no pun intended) resources that are represented by indiscriminate types, such as void* or long. Different resources (and different functions for allocation/deallocation) use this handle type, so specialization is not an option. It's possible to use shared_ptr to handle lifetime management of the resource: HANDLE hPrinter=0; OpenPrinter(_T("Some printer"),&hPrinter,0); if (boost::shared_ptr<void> p(hPrinter,&ClosePrinter)) { } While this works, it doesn't convey the intent of the code (nor preserve it): the resource should typically not be shared, only scoped, and I believe that scoped_ptr<X,D> would be a perfect fit. There are other tools in Boost (outside too, of course) for solving this type of problem, but I think it would be more than cool for scoped_ptr to have this feature; I'd definitely use it in real code. Bjorn Karlsson
bjorn.karlsson@readsoft.com wrote:
HANDLE hPrinter=0; OpenPrinter(_T("Some printer"),&hPrinter,0); if (boost::shared_ptr<void> p(hPrinter,&ClosePrinter)) {
}
While this works, it doesn't convey the intent of the code (nor preserve it): the resource should typically not be shared, only scoped, and I believe that scoped_ptr<X,D> would be a perfect fit.
A zero-overhead scoped_ptr<X, D> would require a helper class here: struct printer_deleter { void operator()(void * pv) const { ClosePrinter(pv); } } scoped_ptr<void, printer_deleter> p(hPrinter); The other option is scoped_ptr<void, void (*) (void *)> p(hPrinter, &ClosePrinter); that would increase sizeof(scoped_ptr) and is of questionable utility. :-) There is always the option to define a dedicated printer class, of course.
participants (2)
-
bjorn.karlsson@readsoft.com
-
Peter Dimov