Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding std::inout_ptr and std::out_ptr in C++23

I've being reading the list of library changes proposed for C++23 and I'm quite curious about the std::out_ptr and std::inout_ptr (their _t siblings). As far as I understand they are some kind of wrapper for smart pointers to be compatible with raw pointers, but I haven't managed to understand them yet. Maybe someone here is familiar with the proposal or may give a less ISO-like explanation or examples?

like image 785
cbuchart Avatar asked Aug 25 '21 07:08

cbuchart


People also ask

What is the difference between auto_ptr and unique_ptr?

unique_ptr is a new facility with a similar functionality, but with improved security. auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.

What is std :: unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Why is std :: Auto_ptr?

std::auto_ptr It may be used to provide exception safety for dynamically allocated objects, for passing ownership of dynamically allocated objects into functions and for returning dynamically allocated objects from functions.

Why was auto_ptr removed?

Since the assignment-semantics was most-disliked feature, they wanted that feature to go away, but since there is code written that uses that semantics, (which standards-committee can not change), they had to let go of auto_ptr, instead of modifying it.


1 Answers

TL;DR - it is for simpler and more seemless interoperability between C out/inout pointer parameters and smart pointers

Longer answer

Let's separate the stuff. std::out_ptr and std::inout_ptr are functions used to create objects of type std::out_ptr_t and std::inout_ptr_t respectively. What are those types and functions for? Let's look at an example inspired by this (for simplicity I replaced generic argument with good ol' int):

int foreign_resetter(int**);
auto up = std::make_unique<int>(5);
 
if (int ec = foreign_resetter(std::inout_ptr(up)) {
    return ec;
}

As you see std::inout_ptr_t created with std::inout_ptr is passed to function taking pointer to pointer to the template argument of std::unique_ptr. Before adding std::inout_ptr_t interoperation with old C in-out pointer parameters was much more cumbersome and error prone. It would look more less like this:

int foreign_resetter(int**);
auto up = std::make_unique<int>(5);
 
int* up_raw = up.release();
if (int ec = foreign_resetter(&up_raw)) {
    return ec;
}
up.reset(up_raw);
like image 85
bartop Avatar answered Oct 22 '22 11:10

bartop