Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Typically what I do in that situation is lightly wrap the API. For instance:

    Image* image = allocate_image(…);
    …
    deallocate_image(image);

    ↓

    struct ImageDeleter {
        void operator()(void* image) const {
            deallocate_image(image);
        }
    };

    unique_ptr<Image, ImageDeleter> image(allocate_image(…));
That certainly can’t work everywhere, but I have yet to be failed by it.


You can reduce verbosity of the code by passing destructor function directly to unique_ptr constructor:

    std::unique_ptr<Image, void (*)(Image *)>(image, deallocate_image);


Cool, thanks for the tip. I meant to offer an example for the general case.


People who don't do this are just asking for it.


That's a lot of boilerplate code. Okay there are macros to wrap such things, but I guess it's things like this that would make the future reader of the code puzzled.


jmq & basman provide examples of how to do it succinctly.


Or, perhaps easier:

scoped_ptr<Image> image(allocate_image(...));




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: