C++14 and SDL2: Managing Resources
ericscottbarr.com
ericscottbarr.com
std::unique_ptr<void,void(*)(void*)> big_ptr(malloc(1), free);
The wasteful thing about this is that you have to store the deleter (free() in this case) right next to your void* for every pointer you manage, so the unique_ptr is twice as large as it needs to be. What you'd like to do is store the deleter in the type of the pointer rather than the pointer itself. It turns out unique_ptr can handle this. If the second template parameter is a type with an overloaded function call operator, then unique_ptr will use that to delete. We can wrap it up like so. template <class T, void F(T *)> struct unique {
struct deleter { void operator()(T *p) { F(p); }; };
typedef std::unique_ptr<T, deleter> ptr;
};
With this helper type you can now declare a similar managed pointer unique<void, free>::ptr small_ptr(malloc(1));
but this time notice that the deleter function is the second template parameter and not an argument to the constructor and the following holds. assert(2 * sizeof(small_ptr) == sizeof(big_ptr));
[1] I used malloc() and free() so those of you following along at home can easily try this out for yourselves.In the examples given, the function pointers in question would be stored on the stack. How many windows should an application be juggling at once that an extra 8 bytes per window is a concern? This seems like a premature optimization to me.
If you're individually rendering blades of grass in a goat simulator, sure. But by the time you're dealing with arbitrary-length application-defined strings (like window names), an extra pointer isn't a big deal.
For me to believe that a small_ptr was worthwhile here, I would have to see some benchmarks, which is how good optimization happens anyway.
I'm all for eliminating that extra bit of overhead and don't claim to be an expert, the whole purpose for me writing this article was to specifically learn about how to write reusable library code. If you have any suggestions for how to pull this off in the general solution I'm all ears!
Thanks again for taking time to comment!
What if you want to add event handlers for window events, change the window title, or even (gasp) throw exceptions instead of constantly check return codes? Wrapping the resource in a class gives you a great place to add this functionality. Without the class you have a nice resource that won't leak but still feels like you're programming C.
In the end, I find it more readable to see unique_ptr and shared_ptr than raw resources. They describe more than just resource management.
Also, I'm not usually one to bash C++ for its syntax (I've written quite a lot of C++ in my days and still use it from time to time) but my god I find that template spaghetti code physically painful to read.
template<typename... Arguments> auto make_window(Arguments&&... args)
{
return detail::make_resource(SDL_CreateWindow, SDL_DestroyWindow, std::forward<Arguments>(args)...);
}
for each resource.Quite honestly at that point I'd sooner use a good old variadic macro, C99 style. I mean, sure, it's arguably less "elegant" and C++-ish but it'll be easier to understand, to maintain and won't spam me with pages of arcane template errors when I forget a colon somewhere, so it'll be easier to debug as well.
That's the double edged sword of the C++ template system I suppose, in order to gain in purity they lost the simplicity of the C macro system without gaining the expressiveness and convenience of the Lisp macro system. In the end, what percentage of C++ coders use templates outside of the STL you think?
(At least the errors have got slightly better in recent g++ releases with colourised error output.)
You don't have to, you can create further helper function calling the generic thing but it's optional.
In these proposed solutions I've not yet seen one that has the capability to do this:
auto window = make_resource(SDL_CreateWindow, SDL_DestroyWindow, ....);
With my solution all you have to do is call make resource with different parameters it automatically works with other C style init/destroy created resources, not just from the SDL library but any C library that follows that practice.Can you try posting what your solution to the general problem would look like?
I suggest that this is somewhat solving the wrong problem.
http://onlinehut.org/2013/01/smart-pointers-are-not-just-for...
though I was trying to use that method to manage handles, not pointers. I eventually had to write a wrapper for handles for it to fulfill the requirements imposed by unique_ptr.
Another use on here suggested a shorter and more efficient way to write the code [0].
You end up exposing the SDL functionality as a normal class object, and everything's much more straightforward.
Let's break it down:
If this weren't library code you mightn't care about proper forwarding (which isn't important anyway since the function you're calling is written in C and C doesn't have lvalue-references!! - unnecessary complexity), so you would sloppily write this as:
template<typename Creator, typename Destructor, typename... Arguments>
auto make_resource(Creator c, Destructor d, Arguments&&... args)
{
typedef decltype(*c(args...)) ResourceType;
return std::unique_ptr<ResourceType, void(*)(ResourceType*)>(c(args...), d);
}
Which is much easier to understand, yes? Your standard passing multiple arguments along thing like you'd normally do when writing a custom printf.Actually, now that I've had time to think about it, you can simpify the original code:
template<typename Creator, typename Destructor, typename... Arguments>
auto make_resource(Creator c, Destructor d, Arguments&&... args)
{
auto r = c(std::forward<Arguments>(args...));
typedef typename std::decay<decltype(*r)>::type ResourceType;
return std::unique_ptr<ResourceType, void(*)(ResourceType*)>(r, d);
}
And again, written sloppily: template<typename Creator, typename Destructor, typename... Arguments>
auto make_resource(Creator c, Destructor d, Arguments&&... args)
{
auto r = c(args...);
typedef decltype(*r) ResourceType;
return std::unique_ptr<ResourceType, void(*)(ResourceType*)>(r, d);
}
Or, if you don't mind repetition of ResourceType: template<typename Creator, typename Destructor, typename... Arguments>
auto make_resource(Creator c, Destructor d, Arguments&&... args)
{
auto r = c(args...);
return std::unique_ptr<decltype(*r), void(*)(decltype(r))>(r, d);
}
Clearer?An alternative way to get the value type is to use std::remove_pointer_t:
using ResourceType = std::remove_pointer_t<decltype(c(args...))>;Your simplification of the original code is great! I like how pulling out the creation of the the resource to its own line makes the typedef and unique_ptr initialization much easier to read (as far as templates go that is, a real sticking point here today).
I have updated my article and attributed the clarification to you, thanks again for your feedback and comments!
With your experience, how would you write a general solution for this problem?
template <typename... Args> inline
std::shared_ptr<SDL_Window> CreateWindow (Args&&... args) {
return std::shared_ptr<SDL_Window> {SDL_CreateWindow(std::forward<Args>(args...)),
&SDL_DestroyWindow};
}
auto window = CreateWindow ("App Name", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
You know, or someone should write a good quality wrapper like you would just expect for any other language (Python, Ruby, whatever). Many here seem to be blasting C++ when nobody is doing any better without a similar level amount of work elsewhere.If you wanted a version of your code with unique_ptr, you would create a SDLDelete struct template. The result would be nearly identical except for an additional type parameter (and the new struct).
Then if you wanted to make "CreateWindow" generic for any of SDL's create/delete pairs... you are basically looking at the OP's make_resource code but slightly different. :P Their version just avoids making a new struct.
Want to look at some tasteful C++ code? Check out LLVM.
Eigen is a quintessential example. It's some of the most complex and inscrutable template code out there but it makes writing numerical code in C++ almost as nice as matlab while also being extremely fast.
http://isocpp.org/files/papers/N3949.pdf
Behind that wonderful STL code lies some crazy code behind the scenes. Is it beautiful? You won't catch me taking that argument! But is it typesafe with minimal overhead and easy for the end user of the code to understand and use? That's the one that's most important. For all the complexity of the template function itself, using it comes down to this:
auto window = sdl2::make_window("App Name", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
Not an angle bracket in sight!https://github.com/swarminglogic/sdl2-cross/blob/master/src/...
https://github.com/swarminglogic/sdl2-cross/blob/master/src/...
Certainly less verbose, and solves the problem quite nicely as far as I've been using it. If someone with some wisdom feel like commenting on it, I'm not averse to learning.
1. Easier to read
2. Easier to use
3. Doesn't rely on bleeding-edge compiler features
I used to do some fun stuff with templates back in the day (CRTP), but I had trouble reading this.
Usually, the number of discrete resources you have to wrap this way is fairly small. I tend to cheat and write header-only libraries because the classes are tiny, don't change much, and shouldn't be used in every compilation unit if you have any semblance of a decent architecture.
Edit: clarified that I mean wrapper classes due to nerd sniping
unique_ptr is not RAII now?
> 1. Easier to read
That's debatable, here ``make_resource`` has to be understood once and will thereafter work with any C constructor/destructor pair. Considering the tone of your comment I guess you mean wrapping each pair in its own object so each of these wrapper objects (and its ownership semantics) has to be understood, and at a fundamental level they're redundant with unique_ptr.
If you don't like the generic thingy and want one wrapper object per call pair, you can just typedef the unique_ptr.
> 2. Easier to use
Easier to use than calling a function and having a unique_ptr with clear ownership semantics?
I'm arguing for introducing thin abstractions over the underlying API to handle lifetime issues, and encapsulate icky, SDL-specific details and types as they arise.
They are definitely redundant with unique_ptr. In return, they're higher-level and more abstract. It's up to the developer to select what level they need to be at. I favor abstraction and readability, others may not.
Wow, sorry, I didn't know you were an internet badass, that changes everything.
As for relaxing, have you considered taking your own advice?
> I'm arguing for introducing thin abstractions over the underlying API to handle lifetime issues, and encapsulate icky, SDL-specific details and types as they arise.
Yes, now that you point it out I can certainly see a careful balancing of the tradeoffs between having to maintain custom code versus the ability to create more extended abstractions in your summary declaration that unique_ptr is hard to read, hard to use and not RAII.
Do you not ever make use of any of the STL templates like std::vector because their implementations are hard to read? Probably not, because they are easy to use and you never have to worry about how they are implemented. Well, here is how you use my function, please tell me how I could make this function call any easier because I honestly would like to know.
auto window = sdl2::create_window("New Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
I wrote a short function that I can reuse with any C based Init/Destroy created resource. Now that it works I never have to think about any of the template magic that went into writing it because using it is dead simple... there aren't even any angle brackets in the call. Not a single proposed "better" solution in this thread has shown the capability of creating resources in the general manner, each one shows the creation of a concrete class which means it has to be duplicated for each type. Which defeats the point of the article.
If you worked with templates back in the day then you probably aren't too familiar with the parameter pack syntax or auto return type deduction, these are new things and yes they are bleeding edge. How is anyone suppose to understand and learn good practices for using these features if they don't make use of them and write about it for others to provide feedback on?
I wrote this article to learn about specific techniques and get feedback on them. It's C++, there's a million ways to skin a cat here... and this article was specifically to address C++14 features. That's why it wasn't titled "C++03 and SDL". I thank you for taking the time to comment but telling someone they shouldn't make use of new compiler features because you aren't familiar with them and then not providing any sort of example yourself to the proposed problem doesn't come across as constructive at all.