3 comments on “The universal resource class pattern

  1. When using std::unique_ptr you should keep in mind that using a nonempty deleter type increases the size of the pointer (when using an empty type, the implementation can make use of the empty base optimization to avoid paying the overhead for an empty member object in the unique_ptr). Thus, and also because it avoids having to pass a release function to unique_ptr’s constructor, it pays of making a deleter struct:

    // ...
    using wrapper1 = std::unique_ptr;

    struct resource_deleter
    {
    auto operator() (resource* r)
    {
    release(r);
    }
    };

    using wrapper2 = std::unique_ptr;

    auto main() -> int
    {
    std::cout // Prints 4, 8, 4 on 32-bit MSVC.
    << "sizeof(resource*) == " << sizeof(resource*) << '\n'
    << "sizeof(wrapper1) == " << sizeof(wrapper1) << '\n'
    << "sizeof(wrapper2) == " << sizeof(wrapper2) << '\n';

    auto w1 = wrapper1{acquire(), &release};
    auto w2 = wrapper2{acquire()}; // No need to pass release.
    }

    (I hope the code is formatted properly, since this blog seems to have neither a preview nor a edit function for comments.)

    • Yeah, the code in the comment didn’t survive the grinder unfortunately – I’m still looking into improvements/alternatives for WordPress to deal with that problem.

      But you have a good point! Shame on me for being lazy.

  2. Pingback: The universal resource class pattern | Software Engineer InformationSoftware Engineer Information

Leave a Reply

Your email address will not be published. Required fields are marked *