Re:Implementing Go's defer keyword in C++
by albinofrenchy on Saturday October 21, 2017 @08:29PM
(#15524430)
You 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.
Re:Implementing Go's defer keyword in C++
by evincarofautumn on Sunday October 22, 2017 @05:10AM
(#15525837)
If 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.
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 :-)