4 ms·
Sometimes you need to wrap C APIs. Sure you could put their guts in a class or struct, but you can also use a unique_ptr for some of the same lifetime stuff. A
by butterisgood 9y ago
Sometimes you need to wrap C APIs. Sure you could put their guts in a class or struct, but you can also use a unique_ptr for some of the same lifetime stuff.
Also, defer in Go always uses the function exit, not the scope. Not sure you can do that in C++. Everything seems scoped.
Maybe don't do this :-)
- albinofrenchy 9y agoYou usually shouldn't use unique_ptr for C api stuff unless you really only need to free it. Typically though there are custom delete/free API calls you need to make, and to use them with unique_ptr you have to pass that function pointer in as the second argument to the unique_ptr constructor. At the very least you should have a C++ function that gives you the unique_ptr back that does the right thing; but at that point you almost might as well just make a class and give it member functions to map the C calls.
- evincarofautumn 9y agoIf you wanted to do things on function exit, you could have an “ENABLE_DEFER” macro that declares a scope for guards; the “DEFER” macro would register the deferred lambda with that scope, not define a new object, and the destructor of the scope would run all the registered guards. Of course, in my C++ code I would just write a class/struct to wrap any RAII-like logic, not use a “defer”. A marginal amount of extra work that pays off in consistency and readability.