std::out_ptr — interface for C-style out parameters.
1#include <memory>23// C API: void create(Handle* handle);4extern "C" void create_c_handle(void** handle);5extern "C" void destroy_c_handle(void* handle);67// Manual (error-prone)8void* raw = nullptr;9create_c_handle(&raw);10std::unique_ptr<void, decltype(&destroy_c_handle)> handle(raw, destroy_c_handle);1112// With std::out_ptr (clean)13std::unique_ptr<void, decltype(&destroy_c_handle)> handle(14 nullptr, destroy_c_handle15);16create_c_handle(std::out_ptr(handle));1718// Works with any smart pointer19std::unique_ptr<int> uptr;20// C function: void fill(int** ptr);21// fill(std::out_ptr(uptr)); // Sets uptr2223// Reset on exception24auto safe = [&] {25 std::unique_ptr<void, decltype(&destroy_c_handle)> h(26 nullptr, destroy_c_handle27 );28 create_c_handle(std::out_ptr(h));29 return h; // Automatically cleaned up on exception30};
Benefits: