In C++23, how do std::out_ptr and std::inout_ptr let a std::unique_ptr receive a handle from a C function's pointer-to-pointer parameter?
answer
- a temporary posing as the out-parameter
- adopted at the end of the full-expression
- out resets first, inout releases
- shared_ptr needs a deleter, or cannot
basics
~10 sstd::out_ptr(p) makes a temporary that stands in for the C function's out-parameter and, at the end of the full-expression, resets p with the handle written into it; std::inout_ptr also passes p's current handle in
solid answer
~40 sC APIs often return a handle through an out-parameter: `int img_open(const char* path, img_image** out);`. C++23's `std::out_ptr(p)` returns a `std::out_ptr_t` temporary that resets `p`, converts to `img_image**` (and to `void**`), and lets the C function write into its own stored pointer. When the temporary is destroyed at the end of the full-expression, it calls `p.reset(handle)` if the handle is not null, so `p` owns it with its custom deleter. `std::inout_ptr(p)` is for functions that read the old handle, free it and write a new one: it passes `p.get()` in and makes `p` give up ownership with `release()`, then adopts the new value. With `std::shared_ptr`, `out_ptr` must be given the deleter again (otherwise the program is ill-formed), and `inout_ptr` is ill-formed altogether.
code
cpp · 24 lines#include <iostream>
#include <memory>
// A C imaging library's API, as its header declares it.
struct img_image { int width; };
int img_open(const char* path, img_image** out) { // 0 on success
if (!path[0]) return -1;
*out = new img_image{640};
return 0;
}
void img_close(img_image* img) { std::cout << "img_close\n"; delete img; }
struct ImgCloser {
void operator()(img_image* p) const noexcept { img_close(p); }
};
using Image = std::unique_ptr<img_image, ImgCloser>;
int main() {
Image scan;
if (img_open("scan.png", std::out_ptr(scan)) != 0) // C++23
return 1;
// the out_ptr_t temporary died when the if condition finished: scan owns the handle
std::cout << "width " << scan->width << '\n';
} // ImgCloser runs herego deeper
Recall that some C functions return a handle through a pointer-to-pointer parameter, and that C++23 adds std::out_ptr to fill a smart pointer from one.
Explain the temporary: it converts to the pointer-to-pointer type, receives the handle, and resets the smart pointer at the end of the full-expression, while inout_ptr passes the old handle in.
Know the edges: adoption only at the semicolon, non-null garbage adopted on failure, shared_ptr needing its deleter for out_ptr and being rejected by inout_ptr.
Weigh adopting C++23 out_ptr across a C-heavy codebase against keeping a project wrapper for compilers that lack it, and set one convention for out-parameter APIs.
## The problem: handles returned through T** Many C libraries create objects through an **output parameter** rather than a return value, keeping the return value for an error code: ```cpp int img_open(const char* path, img_image** out); // 0 on success void img_close(img_image* img); ``` Before C++23, adopting the handle into a smart pointer took a raw intermediate: ```cpp img_image* raw = nullptr; if (img_open(path, &raw) != 0) return error; Image scan(raw); // forgetting this line leaks the handle ``` The window between the C call and the adoption is where leaks hide: an early return, a second call that throws, or a line deleted during a refactor. `&scan.get()` is not an option, because `get()` returns a copy of the pointer, not a reference to the stored one. ## std::out_ptr C++23 adds `std::out_ptr(smart, args...)` in `<memory>`. It returns a `std::out_ptr_t<Smart, Pointer, Args...>` temporary: 1. its constructor resets the smart pointer (`smart.reset()`), so any handle it held is released first; 2. it converts to `Pointer*` (here `img_image**`) and, when the handle type is a raw pointer other than `void*`, to `void**`, so it can be passed straight to the C function; 3. the C function writes the new handle into the temporary's own stored pointer; 4. at the end of the **full-expression**, the temporary's destructor runs and, **if the written pointer is not null**, calls `smart.reset(p, args...)`. So `if (img_open(path, std::out_ptr(scan)) != 0) return error;` adopts the handle at the semicolon, with the deleter that `scan`'s type already names. ## std::inout_ptr Some C functions take an existing handle, free or reallocate it, and write the replacement back through the same parameter. `std::inout_ptr(smart)`: - initialises the temporary's pointer with `smart.get()`, so the C function sees the current handle; - makes the smart pointer give up ownership with `release()` (in the constructor or the destructor, which the standard leaves to the implementation), so the old handle is not closed twice; - adopts whatever non-null value is written back. Using `out_ptr` for such a function would reset the smart pointer first, handing the C function a null pointer instead of the image it should resize. ## Rules with std::shared_ptr | Adaptor | `std::unique_ptr` | `std::shared_ptr` | |---|---|---| | `std::out_ptr(p)` | resets with the existing deleter | ill-formed without extra arguments | | `std::out_ptr(p, deleter)` | `p = unique_ptr(handle, deleter)` | allowed: `reset(handle, deleter)` | | `std::inout_ptr(p)` | releases, then adopts | ill-formed | The `out_ptr` restriction exists because `shared_ptr::reset(q)` without a deleter would replace any custom deleter with `delete`; the standard's note calls that "typically a user error". `inout_ptr` is impossible for `shared_ptr` because shared ownership cannot be released to one caller. libc++ enforces both with a `static_assert`. ## What happens when the C call fails The failure path is where the two adaptors differ most: - **`out_ptr` resets first.** Its constructor calls `reset()` before the C function runs, so a handle the smart pointer already held is closed even if the new open fails. Use a fresh smart pointer, or `inout_ptr`, when the old handle must survive a failed call. - **A failed call that writes nothing adopts nothing.** The temporary's stored pointer starts null, and its destructor only resets when the pointer is non-null, so the smart pointer stays empty and the error code decides what happens next. - **`inout_ptr` re-adopts an untouched handle.** If the C function fails and leaves the old pointer in place, the destructor stores that same value back, so the smart pointer owns it again and nothing leaks or is closed twice. ## Pitfalls - **The adoption happens at the end of the full-expression.** Reading the smart pointer inside the same expression as the C call still sees it empty. - **A garbage value on failure is adopted.** If the C function writes a non-null but invalid pointer when it fails, the smart pointer takes it and later passes it to the deleter. Check the library's contract. - **The deleter is still yours.** `out_ptr` does not supply one: the smart pointer's type, or the extra argument for `shared_ptr`, decides how the handle is closed.
- Why can't you pass &p.get() to the C function instead of std::out_ptr(p)?`get()` returns the stored pointer by value, a prvalue, and the address of a prvalue cannot be taken, so `&p.get()` does not compile. Even if it could, the C function would write into a copy, and `p` would never learn about the new handle. `out_ptr` exists to give the C function a real `T**` and transfer the result into `p` afterwards.
- Why must std::out_ptr be given a deleter when the smart pointer is a std::shared_ptr?Its destructor stores the handle with `reset`. `shared_ptr::reset(q)` without a deleter would make the new control block use `delete`, discarding the `img_close` the handle needs, so the standard makes `out_ptr` with a `shared_ptr` and no extra arguments ill-formed; `std::out_ptr(sp, img_close)` forwards the deleter to `reset`.
- out_ptr hands the C function a pointer to the unique_ptr's own storage
- std::out_ptr(sp) works for shared_ptr and keeps its custom deleter
- &p.get() is a valid way to pass a unique_ptr to a C out-parameter
- inout_ptr can be used with shared_ptr if a deleter is supplied
- The smart pointer owns the new handle the moment the C function writes it
Assumes C++23, where std::out_ptr and std::inout_ptr were added in <memory> (feature-test macro __cpp_lib_out_ptr 202106L); libc++ has them since release 19, and libstdc++ enables them from C++23.