Author: Eric Niebler

  • What are Senders Good For, Anyway?

    Some colleagues of mine and I have been working for the past few years to give C++ a standard async programming model. That effort has resulted in a proposal, P2300, that has been design-approved for C++26. If you know me or if you follow me on social media, you know I’m embarrassingly excited about this work and its potential impact. I am aware, however, that not everybody shares my enthusiasm. I hear these things a lot these days:

    Why would I want to use it?

    Why do we need senders when C++ has coroutines?

    It’s all just too complicated!

    The P2300 crew have collectively done a terrible job of making this work accessible. At the heart of P2300 is a simple, elegant (IMHO) core that brings many benefits, but it’s hard to see that forest for all the trees.

    So let’s make this concrete. In this post, I’ll show how to bring a crusty old C-style async API into the world of senders, and why you might want to do that.

    C(lassic) async APIs

    In a past life I did a lot of Win32 programming. Win32 has several async models to choose from, but the simplest is the good ol’ callback. Async IO APIs like ReadFileEx are shaped like this:

    /// Old-style async C API with a callback
    /// (like Win32's ReadFileEx)
    
    struct overlapped {
      // ...OS internals here...
    };
    
    using overlapped_callback =
      void(int status, int bytes, overlapped* user);
    
    int read_file(FILE*, char* buffer, int bytes,
                  overlapped* user, overlapped_callback* cb);
    

    The protocol is pretty simple: you call read_file passing in the usual arguments plus two extra: a pointer to an “overlapped” structure and a callback. The OS will use the overlapped struct for its own purposes, but the user can stuff data there too that the callback can later use. It looks like this:

    struct my_overlapped : overlapped {
      // ... my extra data goes here ...
    };
    
    void my_callback(int status, int bytes, overlapped* data) {
      auto* my_data = static_cast<my_overlapped*>(data);
    
      // ...use the extra stuff we put in the `my_overlapped`
      //   object...
    
      delete my_data; // clean up
    }
    
    void enqueue_read(FILE* pfile) {
      // Allocate and initialize my_data...
      auto* my_data =
        new my_overlapped{{}, /* my data goes here */ };
    
      int status =
        read_file(pfile, buff, bytes, my_data, my_callback);
      // ...
    }
    

    What happens is this: read_file causes the OS to enqueue an IO operation, saving the overlapped and overlapped_callback pointers with it. When the IO completes, the OS invokes the callback, passing in the pointer to the overlapped struct. I’ve written code like this hundreds of times. You probably have too.

    It’s simple. It works. Why make this more complicated, right?

    C(onfusion of) async APIs

    There’s nothing wrong with the callback API. What’s wrong is that every library that exposes asynchrony uses a slightly different callback API. If you want to chain two async operations from two different libraries, you’re going to need to write a bunch of glue code to map this async abstraction to that async abstraction. It’s the Tower of Babel problem.

    Pieter Brueghel the Elder, Public domain, via Wikimedia Commons Pieter Brueghel the Elder, Public domain, via Wikimedia Commons

    “Look, they are one people, and they have all one language, and this is only the beginning of what they will do; nothing that they propose to do will now be impossible for them. Come, let us go down and confuse their language there, so that they will not understand one another’s speech.” โ€”โ€ŠGenesis 11:6โ€“7

    So, when there are too many incompatible ways to do a thing, what do we do? We make another of course.

    xkcd comic about how standards proliferate https://xkcd.com/927/

    The way to escape this trap is for the C++ standard to endorse one async abstraction. Then all the libraries that expose asynchrony can map their abstractions to the standard one, and we’ll all be able to talk to each other. Babel solved.

    So that is why the C++ Standardization Committee is interested in this problem. Practically speaking, it’s a problem that can only be solved by the standard.

    C(omposable) async APIs

    Which brings us to senders, the topic of P2300. There’s a lot I could say about them (they’re efficient! they’re structured! they compose!), but instead I’m going to show some code and let the code do the talking.

    If we look at the read_file API above, we can identify some different parts:

    1. The allocation of any resources the async operation needs,
    2. The data that must live at a stable address for the duration of the operation (i.e., the overlapped structure),
    3. The initiation of the async operation that enqueues the async IO, and the handling of any initiation failure,
    4. The user-provided continuation that is executed after the async operation completes (i.e., the callback).
    5. The reclamation of any resources allocated in step 1.

    Senders have all these pieces too, but in a uniform shape that makes it possible to work with them generically. In fact, the only meaningful difference between senders and the C-style API is that instead of one callback, in senders there are three: one each for success, failure, and cancellation.

    Step 1: The Allocation

    Our re-imagined read_file API will look like this:

    read_file_sender 
      async_read_file(FILE* file, char* buffer, int size)
      {
        return {file, buffer, size};
      }
    

    The only job of this function is to put the arguments into a sender-shaped object, which looks as follows (explanation after the break):

    namespace stdex = std::execution;
    
    struct read_file_sender
    {
      using sender_concept = stdex::sender_t;             // (1)
    
      template 
      static consteval auto get_completion_signatures()   // (2)
      {
        return stdex::completion_signatures<
          stdex::set_value_t( int, char* ),
          stdex::set_error_t( int ) >();
      }
    
      auto connect( stdex::receiver auto rcvr )           // (3)
      {
        return read_file_operation{{}, {}, pfile, buffer,
                                   size, std::move(rcvr)};
      }
    
      FILE* pfile;
      char* buffer;
      int size;
    };
    

    The job of a sender is to describe the asynchronous operation. (It is also a factory for the operation state, but that’s step 2.) On the line marked “(1)”, we declare this type to be a sender. On the line marked “(2)”, we declare the ways in which this asynchronous operation can complete. We do this using a list of function types. This:

    stdex::set_value_t( int, char* )
    

    … declares that this async operation may complete successfully by passing an int and a char* to the value callback. (Remember, there are three callbacks.) And this:

    stdex::set_error_t( int )
    

    … declares that this async operation may complete in error by passing an int to the error callback. (If this async operation were cancelable, it would declare that with stdex::set_stopped_t().)

    Step 2: The Data

    On the line marked “(3)” above, the connect member function accepts a “receiver” and returns an “operation state”. A receiver is an amalgamation of three callbacks: value, error, and stopped (canceled, more or less). The result of connecting a sender and a receiver is an operation state. The operation state, like the overlapped struct in the C API, is the data for async operation. It must live at a stable address for the duration.

    The connect function returns a read_file_operation object. The caller of connect assumes responsibility for ensuring that this object stays alive and doesn’t move until one of the callbacks is executed. The read_file_operation type looks like this (explanation after the break):

    struct immovable {
      immovable() = default;
      immovable(immovable&&) = delete;
    };
    
    template <class Receiver>
    struct read_file_operation : overlapped, immovable // (1)
    {
      static void _callback(int status, int bytes,     // (2)
                            overlapped* data)
      {
        auto* op =
          static_cast<read_file_operation*>(data);     // (3)
    
        if (status == OK)
          stdex::set_value(std::move(op->rcvr),        // (4)
                           bytes, op->buffer);
        else
          stdex::set_error(std::move(op->rcvr),
                           status);
      }
    
      void start() noexcept                            // (5)
      {
        int status =
          read_file(pfile, buffer, size, this, &_callback);
    
        if (status != OK)
          stdex::set_error(std::move(rcvr), status);
      }
    
      FILE* pfile;
      char* buffer;
      int size;
      Receiver rcvr;
    };
    

    The operation state stores the arguments needed to initiate the async operation as well as the receiver (the three callbacks). Let’s break this down by line.

    • “(1)”: The operation state inherits from overlapped so we can pass a pointer to it into read_file. It also inherits from an immovable struct. Although not strictly necessary, this ensures we don’t move the operation state by accident.
    • “(2)”: We define the overlapped_callback that we will pass to read_file as a class static function.
    • “(3)”: In the callback, we down-cast the overlapped pointer back into a pointer to the read_file_operation object.
    • “(4)”: In the callback, we check the status to see if the operation completed successfully or not, and we call set_value or set_error on the receiver as appropriate.
    • “(5)”: In the start() function — which all operation states must have — we actually initiate the read operation. If the initiation fails, we pass the error to the receiver immediately since the callback will never execute.

    Step 3: The Initiation

    You’ll notice that when we call the sender-ified async_read_file function, we are just constructing a sender. No actual work is started. Then we call connect with a receiver and get back an operation state, but still no work has been started. We’ve just been lining up our ducks, making sure everything is in place at a stable address so we can initiate the work. Work isn’t initiated until .start() is called on the operation state. Only then do we make a call to the C-style read_file API, thereby enqueuing an IO operation.

    All this hoop-jumping becomes important once we start building pipelines and task graphs of senders. Separating the launch of the work from the construction of the operation state lets us aggregate lots of operation states into one that contains all the data needed by the entire task graph, swiveling everything into place before any work gets started. That means we can launch lots of async work with complex dependencies with only a single dynamic allocation or, in some cases, no allocations at all.

    Now I have to fess up. I fibbed a little when I said that the caller of connect needs to keep the operation state alive at a stable address until one of the callbacks is executed. That only becomes true once .start() has been called on it. It is perfectly acceptable to connect a sender to a receiver and then drop the operation state on the floor as long as .start() hasn’t been called yet. But with .start() you’re committed. .start() launches the rockets. There’s no calling them back.

    OK, we’ve constructed the operation state, and we’ve called .start() on it. Now the proverbial ball is in the operating system’s court.

    Step 4: The Continuation

    The operating system does its IO magic. Time passes. When the IO operation is finished, it will invoke the _callback function with a status code, a pointer to the overlapped struct (our read_file_operation) and, if successful, the number of bytes read. The _callback passes the completion information to the receiver that was connect-ed to the sender, and the circle is complete.

    But wait, what about “Step 5: Deallocation”? We never really allocated anything in the first place! The connect function returned the operation state by value. It’s up to the caller of connect, whoever that is, to keep it alive. They may do that by putting it on the heap, in which case they are responsible for cleaning it up. Or, if this async operation is part of a task graph, they may do that by aggregating the operation state into a larger one.

    Step 6: Profit!

    At this point you may be wondering what’s the point to all of this. Senders and receivers, operation states with fiddly lifetime requirements, connect, start, three different callbacks — who wants to manage all of this? The C API was way simpler. It’s true! So why am I so unreasonably excited about all of this?

    The caller of async_read_file doesn’t need to care about any of that.

    The end user, the caller of async_read_file, is not going to be mucking about with receivers and operation states. They are going to be passing senders to generic algorithms. Or even better, they are going to be awaiting senders in coroutines. Look! The following code uses a coroutine task type from the stdexec library.

    stdexec::task< std::string > process_file( FILE* pfile )
    {
      std::string str;
      str.resize( MAX_BUFFER );
    
      auto [bytes, buff] =
        co_await async_read_file(pfile, str.data(), str.size());
    
      str.resize( bytes );
      co_return str;
    }
    

    What wizardry is this? We wrote a sender, not an awaitable, right? But this is working code! See for yourself: https://godbolt.org/z/eGcoj79zY.

    This is where we get to reap the benefits of programming to a standard async model. Generic code, whether from the standard library or from third party libraries, will work with our senders. In the case above, the task<> type from the stdexec library knows how to await anything that looks like a sender. If you have a sender, you can co_await it without doing any extra work.

    P2300 comes with a small collection of generic async algorithms for common async patterns — things like chaining (then), dynamically picking the next task (let_value), grouping senders into one (when_all), and blocking until a sender is complete (sync_wait). It’s a paltry set to be sure, but it will grow with future standards. And as third party libraries begin to adopt this model, more and more async code will work together. Some day very soon you’ll be able to initiate some file IO, read from the network, wait on a timer, listen for a cancellation from the user, wait for them all to complete, and then transfer execution to a thread pool to do more work — whew! — even if each sender and the thread pool came from different libraries.

    Senders, FTW!

    So, back to those pernicious questions folks keep asking me.

    Why would I want to use it?

    You want to use senders because then you can stitch your async operations together with other operations from other libraries using generic algorithms from still other libraries. And so you can co_await your async operations in coroutines without having to write an additional line of code.

    Why do we need senders when C++ has coroutines?

    I hope you realize by now that this isn’t an either/or. Senders are part of the coroutine story. If your library exposes asynchrony, then returning a sender is a great choice: your users can await the sender in a coroutine if they like, or they can avoid the coroutine frame allocation and use the sender with a generic algorithm like then() or when_all(). The lack of allocations makes senders an especially good choice for embedded developers.

    It’s all just too complicated!

    I’ll grant that implementing senders is more involved than using ordinary C-style callbacks. But consuming senders is as easy as typing co_await, or as simple as passing one to an algorithm like sync_wait(). Opting in to senders is opting into an ecosystem of reusable code that will grow over time.

    THAT is why I’m excited about senders.

    (And be honest, was wrapping read_file in a sender really all that hard, after all?)

    "\e"
  • Asynchronous Stacks and Scopes

    In Structured Concurrency, I talk about what structured concurrency is and why it’s a big deal for C++ especially. In this post I discuss some more interesting properties of asynchronous code that is structured: async stacks and async scopes.

    Structured concurrency

    Concurrency is structured when “callee” async functions complete before their “caller” functions resume. This can be done without blocking a thread: the caller (parent) launches the callee (child) task and passes it a handle to itself, effectively telling the child, “When you have your result, call me back. Until then, I’m going to sleep.”

    Immediately after the parent launches the child, the parent function does an ordinary return, often to something like an event loop that is churning through async tasks.

    Async stacks

    When we talk about parent/child async tasks, we are talking about a notional caller/callee relationship: there is a sequence of async operations that has caused the current one to be executing. This chain of operations is exactly like a call stack, but asynchronous. The actual program stack will look nothing like it.

    Anyone who has debugged a multithreaded application knows that the actual program stack doesn’t really tell you what you want to know: How did I get here? All it generally shows is that some event loop is currently processing a certain function. The notional async stack tells you why. From the PoV of the event loop, async work is getting scheduled onto it willy-nilly. The structure of the async computation is a higher-level property of your program’s execution.

    Or it isn’t, as often is the case in multithreaded C++ applications written today. Until C++20, C++ provided no language support for writing structured async code, and so that code is typically unstructured: no parent/child relationships exist at all. Work is scheduled with fire-and-forget semantics, using ad hoc out-of-band mechanisms to synchronize work, propagate values and errors, and keep data alive. It’s like programming with jmp instructions instead of functions — no stack at all.

    Async scopes

    C++ programmers have simply accepted this state of affairs because they didn’t have anything better. Until C++20 introduced coroutines, that is. Coroutines are transformative, not because the syntax is nice, but because they cause async scopes to coincide with lexical scopes.

    What’s an async scope? If an async stack is a chain of async function activations, then an async scope corresponds to the activation of a single async function. It encompasses all the state — variables and whatnot — that need to live for the duration of an async operation and all of its nested child operations. With callbacks, the async scope spans disjoint lexical scopes: it starts when an async function is called and ends when the callback returns — that is, if your code is structured.

    If your async code is unstructured, there are no async scopes at all because there’s no notion of child operations that nest within parents. Or you could say there are overlapping scopes. Unsurprisingly, this makes resource management hard, which is why so much async C++ is littered with std::shared_ptr.

    Coroutines

    Which brings us back to coroutines. For coroutines, the async scope starts when the coroutine is first called and it ends when the coroutine returns (or co_returns I should say). Well, that’s just like ordinary functions with ordinary scopes! Which is exactly the point.

    Forget that coroutines make async code read like synchronous code. Forget that the syntax is nice. The overwhelming benefit of coroutines in C++ is its ability to make your async scopes line up with lexical scopes because now we get to leverage everything we already know about functions, scopes, and resource management. Do you need some piece of data to live as long as this async operation? No problem. Make it a local variable in a coroutine.

    Beyond coroutines…

    Coroutines make the idea of structured concurrency obvious by manifesting it in code. We don’t have to worry about notional stacks and scopes.1 There’s the scope right there, between the curly braces! Here’s the mindbender though: Just as Dorothy could have gone home to Kansas any time she wanted, so too could we have been structuring our async code all along.

    Here’s a dirty secret about coroutines: they’re just sugar over callbacks; everything after the co_await in a coroutine is a callback. The compiler makes it so. And damn, we’ve had callbacks forever, we’ve just been misusing them. Structured concurrency has been just three heel-clicks away all this time.

    Language support makes it much easier to ensure that child operations nest within parents, but with the right library abstractions, structured concurrency in C++ is totally possible without coroutines — and damn efficient.

    Next post, I’ll introduce these library abstractions, which are the subject of the C++ standard proposal P2300, and what the library abstractions bring over and above C++20 coroutines.


    1. Well, actually we still do until debuggers grok coroutines and can let us view the async stack. ↩

  • Structured Concurrency

    TL;DR: “Structured concurrencyโ€ refers to a way to structure async computations so that child operations are guaranteed to complete before their parents, just the way a function is guaranteed to complete before its caller. This sounds simple and boring, but in C++ it’s anything but. Structured concurrency โ€” most notably, C++20 coroutines โ€” has profound implications for the correctness and the simplicity of async architecture. It brings the Modern C++ style to our async programs by making async lifetimes correspond to ordinary C++ lexical scopes, eliminating the need for reference counting to manage object lifetime.

    Structured Programming and C++

    Back in the 1950’s, the nascent computing industry discovered structured programming: that high-level programming languages with lexical scopes, control structures, and subroutines resulted in programs that were far easier to read, write, and maintain than programming at the assembly level with test-and-jump instructions and goto. The advance was such a quantum leap that nobody talks about structured programming anymore; it’s just “programmingโ€.

    C++, more so than any other language, leverages structured programming to the hilt. The semantics of object lifetime mirror โ€” and are tied to โ€” the strict nesting of scopes; i.e., the structure of your code. Function activations nest, scopes nest, and object lifetimes nest. Objects’ lifetimes end with a scope’s closing curly brace, and objects are destroyed in the reverse order of their construction to preserve the strict nesting.

    The Modern C++ programming style is built on this structured foundation. Objects have value semantics โ€” they behave like the ints โ€” and resources are cleaned up in destructors deterministically, which guarantees structurally that resources aren’t used after their lifetimes have ended. This is very important.

    When we abandon this strict nesting of scopes and lifetimes โ€” say, when we reference count an object on the heap, or when we use the singleton pattern โ€” we are fighting against the strengths of the language rather than working with them.

    The Trouble With Threads

    Writing correct programs in the presence of concurrency is far more difficult than in single-threaded code. There are lots of reasons for this. One reason is that threads, like singletons and dynamically allocated objects, scoff at your puny nested scopes. Although you can use the Modern C++ style within a thread, when logic and lifetimes are scattered across threads, the hierarchical structure of your program is lost. The tools we use to manage complexity in single-threaded code โ€” in particular, nested lifetimes tied to nested scopes โ€” simply don’t translate to async code.

    To see what I mean, let’s look at what happens when we take a simple synchronous function and make it asynchronous.

    void computeResult(State & s);
    
    int doThing() {
      State s;
      computeResult(s);
      return s.result;
    }
    

    doThing() is simple enough. It declares some local state, calls a helper, then returns some result. Now imagine that we want to make both functions async, maybe because they take too long. No problem, let’s use Boost futures, which support continuation chaining:

    boost::future<void> computeResult(State & s);
    
    boost::future<int> doThing() {
      State s;
      auto fut = computeResult(s);
      return fut.then(
        [&](auto&&) { return s.result; }); // OOPS
    }
    

    If you’ve programmed with futures before, you’re probably screaming, “Nooooo!โ€ The .then() on the last line queues up some work to run after computeResult() completes. doThing() then returns the resulting future. The trouble is, when doThing() returns, the lifetime of the State object ends, and the continuation is still referencing it. That is now a dangling reference, and will likely cause a crash.

    What has gone wrong? Futures let us compute with results that aren’t available yet, and the Boost flavor lets us chain continuations. But the continuation is a separate function with a separate scope. We often need to share data across those separate scopes. No more tidy nested scopes, no more nested lifetimes. We have to manage the lifetime of the state manually, something like this:

    boost::future<void>
    computeResult(shared_ptr<State> s); // addref
                                        // the state
    
    boost::future<int> doThing() {
      auto s = std::make_shared<State>();
      auto fut = computeResult(s);
      return fut.then(
        [s](auto&&) { return s.result; }); // addref
                                           // the state
    }
    

    Since both async operations refer to the state, they both need to share responsibility to keep it alive.

    Another way to think about this is: what is the lifetime of this asynchronous computation? It starts when doThing() is called, but it doesn’t end until the continuation โ€” the lambda passed to future.then() โ€” returns. There is no lexical scope that corresponds to that lifetime. And that is the source of our woes.

    Unstructured Concurrency

    The story gets more complicated yet when we consider executors. Executors are handles to executions contexts that let you schedule work onto, say, a thread or thread pool. Many codebases have some notion of an executor, and some let you schedule things with a delay or with some other policy. This lets us do cool things, like move a computation from an IO thread pool to a CPU thread pool, or retry an async operation with a delay. Handy, but like goto it is a very low-level control structure that tends to obfuscate rather than clarify.

    For instance, I recently came across an algorithm that uses executors and callbacks (called Listeners here) that retries the async allocation of some resource. Below is a greatly abridged version. It is described after the break.

    // This is a continuation that gets invoked when
    // the async operation completes:
    struct Manager::Listener : ListenerInterface {
      shared_ptr<Manager> manager_;
      executor executor_;
      size_t retriesCount_;
    
      void onSucceeded() override {
        /* ...yay, allocation succeeded... */
      }
      void onFailed() override {
        // When the allocation fails, post a retry
        // to the executor with a delay
        auto alloc = [manager = manager_]() {
          manager->allocate();
        };
        // Run "alloc" at some point in the future:
        executor_.execute_after(
          alloc, 10ms * (1 << retriesCount_));
      }
    };
    
    // Try asynchronously allocating some resource
    // with the above class as a continuation
    void Manager::allocate() {
      // Have we already tried too many times?
      if (retriesCount_ > kMaxRetries) {
        /* ...notify any observers that we failed */
        return;
      }
    
      // Try once more:
      ++retriesCount_;
      allocator_.doAllocate(
        make_shared<Listener>(
          shared_from_this(),
          executor_,
          retriesCount_));
    }
    

    The allocate() member function first checks to see if the operation has already been retried too many times. If not it calls a helper doAllocate() function, passing in a callback to be notified on either success or failure. On failure, the handler posts deferred work to the executor, which will call allocate() back, thus retrying the allocation with a delay.

    This is a heavily stateful and rather circuitous async algorithm. The logic spans many functions and several objects, and the control and data flow is not obvious. Note the intricate ref-counting dance necessary to keep the objects alive. Posting the work to an executor makes it even harder. Executors in this code have no notion of continuations, so errors that happen during task execution have nowhere to go. The allocate() function can’t signal an error by throwing an exception if it wants any part of the program to be able to recover from the error. Error handling must be done manually and out-of-band. Ditto if we wanted to support cancellation.

    This is unstructured concurrency: we queue up async operations in an ad hoc fashion; we chain dependent work, use continuations or “strandโ€ executors to enforce sequential consistency; and we use strong and weak reference counts to keep data alive until we are certain it’s no longer needed. There is no formal notion of task A being a child of task B, no way to enforce that child tasks complete before their parents, and no one place in the code that we can point to and say, “Here is the algorithm.”

    If you don’t mind the analogy, the hops through the executor are a bit like goto statements that are non-local in both time and space: “Jump to this point in the program, X milliseconds from now, on this particular thread.”

    That non-local discontinuity makes it hard to reason about correctness and efficiency. Scale unstructured concurrency up to whole programs handling lots of concurrent real-time events, and the incidental complexity of manually handling out-of-band asynchronous control and data flow, controlling concurrent access to shared state, and managing object lifetime becomes overwhelming.

    Structured Concurrency

    Recall that in the early days of computing, unstructured programming styles rapidly gave way to structured styles. With the addition of coroutines to C++, we are seeing a similar phase shift happening today to our asynchronous code. If we were to rewrite the above retry algorithm in terms of coroutines (using Lewis Baker’s popular cppcoro library), it might look something like this:

    // Try asynchronously allocating some resource
    // with retry:
    cppcoro::task<> Manager::allocate() {
      // Retry the allocation up to kMaxRetries
      // times:
      for (int retriesCount = 1;
           retriesCount <= kMaxRetries;
           ++retriesCount) {
        try {
          co_await allocator_.doAllocate();
          co_return; // success!
        } catch (...) {}
    
        // Oops, it failed. Yield the thread for a
        // bit and then retry:
        co_await scheduler_.schedule_after(
          10ms * (1 << retriesCount));
      }
    
      // Error, too many retries
      throw std::runtime_error(
        "Resource allocation retry count exceeded.");
    }
    

    Aside: This replaces the executor_ with a scheduler_ that implements cppcoro’s DelayedScheduler concept.

    Let’s list the ways in which this is an improvement:

    1. It’s all in one function! Good locality.
    2. The state (like retriesCount) can be maintained in local variables instead of as members of objects that need to be ref-counted.
    3. We can use ordinary C++ error handling techniques.
    4. We are guaranteed structurally that the async call to allocator_.doAllocate() completes before this function continues executing.

    Point (4) has profound implications. Consider the trivial example from the beginning of the article. The following re-implementation in terms of coroutines is perfectly safe:

    cppcoro::task<> computeResult(State & s);
    
    cppcoro::task<int> doThing() {
      State s;
      co_await computeResult(s);
      co_return s.result;
    }
    

    The above code is safe because we know that computeResult completes before doThing is resumed and thus before s is destructed.

    With structured concurrency, it is perfectly safe to pass local variables by reference to child tasks that are immediately awaited.

    Cancellation

    Taking a structured approach to concurrency, where the lifetime of concurrent operations is strictly nested within the lifetime of resources that it uses and is tied to program scopes, allows us to avoid needing to use garbage collection techniques like shared_ptr to manage lifetime. This can lead to code that is more efficient, requiring fewer heap-allocations and fewer atomic reference-counting operations, as well as code that is easier to reason about and is less bug-prone. However, one implication of this approach is that it means that we must always join and wait for child operations before the parent operation can complete. We can no longer just detach from those child operations and let the resources get cleaned up automatically when their ref-counts drop to zero. To avoid having to wait unnecessarily long times for child operations whose results are no longer needed, we need a mechanism to be able to cancel those child operations so that they complete quickly. Thus the structured concurrency model requires deep support for cancellation to avoid introducing unnecessary latency.

    Note that we rely on structured lifetime and structured concurrency every time we pass a local variable to a child coroutine by reference. We must ensure that the child coroutine has completed and is no longer using that object before the parent coroutine exits the scope of that local variable and destroys it.

    Structured Concurrency > Coroutines

    When I talk about “structured concurrency,โ€ I am not just talking about coroutines โ€” although that is its most obvious manifestation. To see what I mean, let’s talk briefly about what coroutines are and what they are not. In particular, there is nothing inherently concurrent about C++ coroutines at all! They are really just a way to get the compiler to carve your function up into callbacks for you.

    Consider the simple coroutine above:

    cppcoro::task<> computeResult(State & s);
    
    cppcoro::task<int> doThing() {
      State s;
      co_await computeResult(s);
      co_return s.result;
    }
    

    What does co_await here mean? The trite answer is: it means whatever the author of cppcoro::task<> wants it to mean (within certain bounds). The fuller answer is that co_await suspends the current coroutine, bundles up the rest of the coroutine (here, the statement co_return s.result;) as a continuation, and passes it to the awaitable object (here, the task<> returned by computeResult(s)). That awaitable will typically store it somewhere so it can be invoked later, when the child task completes. That’s what cppcoro::task<> does, for instance.

    In other words, the task<> type and the coroutines language feature conspire together to layer “structured concurrencyโ€ on top of boring ol’ callbacks. That’s it. That’s the magic. It’s all just callbacks, but callbacks in a very particular pattern, and it is that pattern that makes this “structured.โ€ The pattern ensures that child operations complete before parents, and that property is what brings the benefits.

    Once we recognize that structured concurrency is really just callbacks in a particular pattern, we realize that we can achieve structured concurrency without coroutines. Programming with callbacks is nothing new, of course, and the patterns can be codified into a library and made reusable. That’s what libunifex does. If you follow C++ standardization, it is also what the sender/receiver abstraction from the Executors proposal does.

    Using libunifex as a basis for structured concurrency, we can write the example above as follows:

    unifex::any_sender_of<> computeResult(State & s);
    
    auto doThing() {
      return unifex::let_with(
        // Declare a "local variable" of type State:
        [] { return State{}; },
        // Use the local to construct an async task:
        [](State & s) {
          return unifex::transform(
            computeResult(s),
            [&] { return s.result; });
        });
    }
    

    Why would anybody write that when we have coroutines? You would certainly need a good reason, but I can think of a few. With coroutines, you have an allocation when a coroutine is first called, and an indirect function call each time it is resumed. The compiler can sometimes eliminate that overhead, but sometimes not. By using callbacks directly โ€” but in a structured concurrency pattern โ€” we can get many of the benefits of coroutines without the tradeoffs.

    That style of programming makes a different tradeoff, however: it is far harder to write and read than the equivalent coroutine. I think that >90% of all async code in the future should be coroutines simply for maintainability. For hot code, selectively replace coroutines with the lower-level equivalent, and let the benchmarks be your guide.

    Concurrency

    I mention above that coroutines aren’t inherently concurrent; they’re just a way of writing callbacks. Coroutines are inherently sequential in nature and the laziness of task<> types โ€” where a coroutine starts suspended and doesn’t start executing until it is awaited โ€” means that we can’t use it to introduce concurrency in the program. Existing future-based code often assumes that the operation has already started eagerly, introducing ad hoc concurrency that you need to be careful to prune back. That forces you to re-implement concurrency patterns over and over in an ad hoc fashion.

    With structured concurrency, we codify concurrency patterns into reusable algorithms to introduce concurrency in a structured way. For instance, if we have a bunch of tasks and would like to wait until they have all completed and return their results in a tuple, we pass them all to the cppcoro::when_all and co_await the result. (Libunifex also has a when_all algorithm.)

    At present, neither cppcoro nor libunifex has a when_any algorithm, so you can’t launch a bunch of concurrent operations and return when the first one completes. It’s a very important and interesting foundational algorithm, though. To maintain the guarantees of structured concurrency, when the first child task completes, when_any should request cancellation on all the other tasks and then wait for them all to finish. The utility of this algorithm depends upon all async operations in your program responding promptly to cancellation requests, which demonstrates just how important deep support for cancellation is in modern async programs.

    Migration

    So far, I’ve discussed what structured concurrency is and why it matters. I haven’t discussed how we get there. If you are already using coroutines to write async C++, then congrats. You may keep enjoying the benefits of structured concurrency, perhaps with a deeper understanding and appreciation for why coroutines are so transformative.

    For codebases that lack structured concurrency, deep support for cancellation, or maybe even an abstraction for asynchrony, the job is hard. It may even start with introducing complexity in order to carve out an island in which the surrounding code provides the guarantees that structured concurrency patterns require. This includes, for instance, creating the impression of prompt cancellation of scheduled work, even when the underlying execution contexts don’t offer that directly. That added complexity can be isolated in a layer, and the islands of structured concurrency can be built on top. Then the simplifying work can begin, taking future- or callback-style code and converting them to coroutines, teasing out parent/child relationships, ownership, and lifetime.

    Summary

    Adding co_await makes a synchronous function asynchronous, without disturbing the structure of the computation. The async operation being awaited necessarily completes before the calling function does, just like ordinary function calls. The revolution is: nothing changes. Scopes and lifetimes still nest as they always have, except now the scopes are discontinuous in time. With raw callbacks and futures, that structure is lost.

    Coroutines, and structured concurrency more generally, bring the advantages of the Modern C++ style โ€” value semantics, algorithm-driven design, clear ownership semantics with deterministic finalization โ€” into our async programming. It does that because it ties async lifetimes back to ordinary C++ lexical scopes. Coroutines carve our async functions up into callbacks at suspension points, callbacks that get called in a very specific pattern to maintain that strict nesting of scopes, lifetimes, and function activations.

    We sprinkle co_await in our code and we get to continue using all our familiar idioms: exceptions for error handling, state in local variables, destructors for releasing resources, arguments passed by value or by reference, and all the other hallmarks of good, safe, and idiomatic Modern C++.

    Thanks for reading.


    If you want to hear more about structured concurrency in C++, be sure to check out Lewis Baker’s CppCon talk from 2019 about it.

    "\e"
  • Standard Ranges

    As you may have heard by now, Ranges got merged and will be part of C++20. This is huge news and represents probably the biggest shift the Standard Library has seen since it was first standardized way back in 1998.

    This has been a long time coming. Personally, I’ve been working toward this since at least November 2013, when I opined, “In my opinion, itโ€™s time for a range library for the modern world,” in a blog post on input ranges. Since then, I’ve been busy building that modern range library and nailing down its specification with the help of some very talented people.

    Future blog posts will discuss how we got here and the gritty details of how the old stuff and the new stuff play together (we’re C++ programmers, we love gritty details), but this post is strictly about the what.

    What is coming in C++20?

    All of the Ranges TS โ€” and then some โ€” will ship as part of C++20. Here’s a handy table of all the major features that will be shipping as part of the next standard:

    Feature Example
    Fundamental concepts std::Copyable<T>
    Iterator and range concepts std::InputIterator<I>
    New convenience iterator traits std::iter_value_t<I>
    Safer range access functions std::ranges::begin(rng)
    Proxy iterator support std::iter_value_t<I> tmp =
        std::ranges::iter_move(i);
    Contiguous iterator support std::ContiguousIterator<I>
    Constrained algorithms std::ranges::sort(v.begin(), v.end());
    Range algorithms std::ranges::sort(v);
    Constrained function objects std::ranges::less
    Generalized callables std::ranges::for_each(v, &T::frobnicate);
    Projections std::ranges::sort(employees, less{},
        &Employee::id);
    Range utilities struct my_view : std::view_interface<my_view> {
    Range generators auto indices = std::view::iota(0u, v.size());
    Range adaptors for (auto x : v | std::view::filter(pred)) {

    Below, I say a few words about each. But first I wanted to revisit an old coding challenge and recast its solution in terms of standard C++20.

    Pythagorian Triples, Revisited

    Some years ago now, I wrote a blog post about how to use ranges to generate an infinite list of Pythagorean triples: 3-tuples of integers where the sum of the squares of the first two equals the square of the third.

    Below is the complete solution as it will look in standard C++20. I take the solution apart after the break.

    // A sample standard C++20 program that prints
    // the first N Pythagorean triples.
    #include <iostream>
    #include <optional>
    #include <ranges>   // New header!
    
    using namespace std;
    
    // maybe_view defines a view over zero or one
    // objects.
    template<Semiregular T>
    struct maybe_view : view_interface<maybe_view<T>> {
      maybe_view() = default;
      maybe_view(T t) : data_(std::move(t)) {
      }
      T const *begin() const noexcept {
        return data_ ? &*data_ : nullptr;
      }
      T const *end() const noexcept {
        return data_ ? &*data_ + 1 : nullptr;
      }
    private:
      optional<T> data_{};
    };
    
    // "for_each" creates a new view by applying a
    // transformation to each element in an input
    // range, and flattening the resulting range of
    // ranges.
    // (This uses one syntax for constrained lambdas
    // in C++20.)
    inline constexpr auto for_each =
      []<Range R,
         Iterator I = iterator_t<R>,
         IndirectUnaryInvocable<I> Fun>(R&& r, Fun fun)
            requires Range<indirect_result_t<Fun, I>> {
          return std::forward<R>(r)
            | view::transform(std::move(fun))
            | view::join;
      };
    
    // "yield_if" takes a bool and a value and
    // returns a view of zero or one elements.
    inline constexpr auto yield_if =
      []<Semiregular T>(bool b, T x) {
        return b ? maybe_view{std::move(x)}
                 : maybe_view<T>{};
      };
    
    int main() {
      // Define an infinite range of all the
      // Pythagorean triples:
      using view::iota;
      auto triples =
        for_each(iota(1), [](int z) {
          return for_each(iota(1, z+1), [=](int x) {
            return for_each(iota(x, z+1), [=](int y) {
              return yield_if(x*x + y*y == z*z,
                make_tuple(x, y, z));
            });
          });
        });
    
        // Display the first 10 triples
        for(auto triple : triples | view::take(10)) {
          cout << '('
               << get<0>(triple) << ','
               << get<1>(triple) << ','
               << get<2>(triple) << ')' << '\n';
      }
    }
    

    The above program prints the following:

    (3,4,5)
    (6,8,10)
    (5,12,13)
    (9,12,15)
    (8,15,17)
    (12,16,20)
    (7,24,25)
    (15,20,25)
    (10,24,26)
    (20,21,29)
    

    This program is (lazily) generating an infinite list of Pythagorean triples, taking the first 10, and printing them out. Below is a quick rundown on how it works. Along the way, I’ll point out the parts of that solution that will be standard starting in C++20.

    main()

    First, let’s look at main, which creates the infinite list of triples and prints out the first 10. It makes repeated use of for_each to define the infinite list. A use like this:

    auto x = for_each( some-range, [](auto elem) {
      return some-view;
    } );
    

    means: For every element in some-range, call the lambda. Lazily collect all the views thus generated and flatten them into a new view. If the lambda were to return view::single(elem), for instance — which returns a view of exactly one element — then the above is a no-op: first carve some-range into N subranges of 1-element each, then flatten them all back into a single range.

    Armed with that knowledge, we can make sense of the triply-nested invocations of for_each:

    for_each(iota(1), [](int z) {
      return for_each(iota(1, z+1), [=](int x) {
        return for_each(iota(x, z+1), [=](int y) {
    

    This code is generating every combination of integers x, y, and z in some order (selecting the bounds so that x and y are never larger than z, because those can’t be Pythagorean triples). At each level we create structure: we start with a single range (iota(1), described below), and then get a range of ranges where each inner range corresponds to all the combinations that share a value for z. Those inner ranges are themselves further decomposed into subranges, each of which represents all the combinations that share a value of x. And so on.

    The innermost lambda has x, y, and z and can decide whether to emit the triple or not:

    return yield_if(x*x + y*y == z*z,
        make_tuple(x, y, z));
    

    yield_if takes a Boolean (have we found a Pythagorean triple?) and the triple, and either emits an empty range or a 1-element range containing the triple. That set of ranges then gets flattened, flattened, and flattened again into the infinite list of the Pythagorean triples.

    We then pipe that infinite list to view::take(10), which truncates the infinite list to the first 10 elements. Then we iterate over those elements with an ordinary range-based for loop and print out the results. Phwew!

    Now that we have a high-level understanding of what this program is doing, we can take a closer look at the individual components.

    view::iota

    This is a very simple view. It takes either one or two objects of Incrementable type. It builds a range out of them, using the second argument as the upper bound of a half-closed (i.e., exclusive) range, taking the upper bound to be an unreachable sentinel if none is specified (i.e., the range is infinite). Here we use it to build a range of integers, but any incrementable types will do, including iterators.

    The name “iota” comes from the std::iota numeric algorithm, which itself has an interesting naming history.

    for_each

    The range-v3 library comes with view::for_each and yield_if, but those haven’t been proposed yet. But view::for_each is a trivial composition of view::transform and view::join which will be part of C++20, so we can implement it as follows:

    inline constexpr auto for_each =
      []<Range R,
         Iterator I = iterator_t<R>,
         IndirectUnaryInvocable<I> Fun>(R&& r, Fun fun)
           requires Range<indirect_result_t<Fun, I>> {
         return std::forward<R>(r)
           | view::transform(std::move(fun))
           | view::join;
      };
    

    This declares an object for_each that is a C++20 constrained generic lambda with explicitly specified template parameters. “Range” and “IndirectUnaryInvocable” are standard concepts in C++20 that live in namespace std. They constrain the arguments r and fun of the lambda to be a range (duh) and a function that is callable with the values of the range. We then further constrain the lambda with a trailing requires clause, ensuring that the function’s return type must be a Range as well. indirect_result_t will also be standard in C++20. It answers the question: if I call this function with the result of dereferencing this iterator, what type do I get back?

    The lambda first lazily transforms the range r by piping it to view::transform, moving fun in. view:: is a namespace within std:: in which all the new lazy range adaptors live. Since fun returns a Range (we required that!), the result of the transformation is a range of ranges. We then pipe that to view::join to flatten the ranges into one big range.

    The actual code, lines 6-8, kind of gets lost in the sea of constraints, which are not strictly necessary to use the library; I’m being a bit pedantic for didactic purposes here, so please don’t let that trip you up.

    I also could have very easily written for_each as a vanilla function template instead of making it an object initialized with a constrained generic lambda. I opted for an object in large part because I wanted to demonstrate how to use concepts with lambdas in C++20. Function objects have other nice properties, besides.

    yield_if

    yield_if is simpler conceptually, but it requires a little legwork on our part. It is a function that takes a Boolean and an object, and it returns either an empty range (if the Boolean is false), or a range of length one containing the object. For that, we need to write our own view type, called maybe_view, since there isn’t one in C++20. (Not yet, at least. There is a proposal.)

    Writing views is made a little simpler with the help of std::view_interface, which generates some of the boilerplate from begin() and end() functions that you provide. view_interface provides some handy members like .size(), .operator[], .front(), and .back().

    maybe_view is reproduced below. Notice how it is trivially implemented in terms of std::optional and std::view_interface.

    template<Semiregular T>
    struct maybe_view : view_interface<maybe_view<T>> {
      maybe_view() = default;
      maybe_view(T t) : data_(std::move(t)) {
      }
      T const *begin() const noexcept {
        return data_ ? &*data_ : nullptr;
      }
      T const *end() const noexcept {
        return data_ ? &*data_ + 1 : nullptr;
      }
    private:
      optional<T> data_{};
    };
    

    Once we have maybe_view, the implementation of yield_if is also trivial. It returns either an empty maybe_view, or one containing a single element, depending on the Boolean argument.

    inline constexpr auto yield_if =
      []<Semiregular T>(bool b, T x) {
        return b ? maybe_view{std::move(x)}
                 : maybe_view<T>{};
      };
    

    Note: maybe_view owns its elements. It is generally a violation of the View concept’s semantic requirements for a view to own its elements because it gives the type’s copy and move operations O(N) behavior. However, in this case — where N is either 0 or 1 — we just squeak by.

    And that’s it. This program demonstrates how to use view::iota, view::transform, view::join, view_interface, and some standard concepts to implement a very useful bit of library functionality, and then uses it to construct an infinite list with some interesting properties. If you have used list comprehensions in Python or Haskell, this should feel pretty natural.

    But these features are just a tiny slice of the range support in C++20. Below, I go through each row of the table at the top of the post, and give an example of each.

    Fundamental Concepts

    The C++20 Standard Library is getting a host of generally useful concept definitions that users can use in their own code to constrain their templates and to define higher-level concepts that are meaningful for them. These all live in the new <concepts> header, and they include things like Same<A, B>, ConvertibleTo<From, To>, Constructible<T, Args...>, and Regular<T>.

    Say for instance that youย have a thread pool class with an enqueue member function that takes something that is callable with no arguments. Today, you would write it like this:

    struct ThreadPool {
      template <class Fun>
      void enqueue( Fun fun );
    };
    

    Users reading this code might wonder: what are the requirements on the type Fun? We can enforce the requirement in code using C++20’s std::Invocable concept, along with the recently-added support for abreviated function syntax:

    #include <concepts>
    
    struct ThreadPool {
      void enqueue( std::Invocable auto fun );
    };
    

    This states that fun has to be invocable with no arguments. We didn’t even have to type template <class ...>! (std::Invocable<std::error_code &> auto fun would declare a function that must be callable with a reference to a std::error_code, to take another example.)

    Iterator and Range Concepts

    A large part of the Standard Library concerns itself with containers, iterators, and algorithms, so it makes sense that the conceptual vocabulary would be especially rich in this area. Look for useful concept definitions like Sentinel<S, I>, InputIterator<I>, and RandomAccessIterator<I> in the <iterator> header, in addition to useful compositions like IndirectRelation<R, I1, I2> which test that R imposes a relation on the result of dereferencing iterators I1 and I2.

    Say for example that you have a custom container type in your codebase called SmallVector that, like std::vector, can be initialized by passing it two iterators denoting a range. We can write this with concepts from <iterator> and <concepts> as follows:

    template <std::Semiregular T>
    struct SmallVector {
      template <std::InputIterator I>
        requires std::Same<T, std::iter_value_t<I>>
      SmallVector( I i, std::Sentinel<I> auto s ) {
        // ...push back all elements in [i,s)
      }
      // ...
    

    Likewise, this type can get a constructor that takes a range directly using concepts defined in the new <ranges> header:

      // ... as before
      template <std::InputRange R>
        requires std::Same<T, std::range_value_t<R>>
      explicit SmallVector( R && r )
        : SmallVector(std::ranges::begin(r),
                      std::ranges::end(r)) {
      }
    };
    

    Note: range_value_t<R> hasn’t been formally accepted yet. It is an alias for iter_value_t<iterator_t<R>>.

    New Convenience Iterator Traits

    In C++17, if you want to know the value type of an iterator I, you have to type typename std::iterator_traits<I>::value_type. That is a mouthful. In C++20, that is vastly shortened to std::iter_value_t<I>. Here are the newer, shorter type aliases and what they mean:

    New iterator type alias Old equivalent
    iter_difference_t<I> typename iterator_traits<I>::difference_type
    iter_value_t<I> typename iterator_traits<I>::value_type
    iter_reference_t<I> typename iterator_traits<I>::reference
    iter_rvalue_reference<I> no equivalent, see below

    There is no iter_category_t<I> to get an iterator’s tag type because tag dispatching is now passรฉ. Now that you can dispatch on iterator concept using language support, there is no need for tags.

    Safe Range Access Functions

    What is wrong with std::begin and std::end? Surprise! they are not memory safe. Consider what this code does:

    extern std::vector<int> get_data();
    auto it = std::begin(get_data());
    int i = *it; // BOOM
    

    std::begin has two overloads for const and non-const lvalues. Trouble is, rvalues bind to const lvalue references, leading to the dangling iterator it above. If we had instead called std::ranges::begin, the code would not have compiled.

    ranges::begin has other niceties besides. It does the ADL two-step for you saving you from remembering to type using std::begin; in generic code. In other words, it dispatches to a begin() free function found by ADL, but only if it returns an Iterator. That’s an extra bit of sanity-checking that you won’t get from std::begin.

    Basically, prefer ranges::begin in all new code in C++20 and beyond. It’s more better.

    Prvalue and Proxy Iterator Support

    The C++98 iterator categories are fairly restrictive. If your iterator returns a temporary (i.e., a prvalue) from its operator*, then the strongest iterator category it could model was InputIterator. ForwardIterator required operator* to return by reference. That meant that a trivial iterator that returns monotonically increasing integers by value, for example, cannot satisfy ForwardIterator. Shame, because that’s a useful iterator! More generally, any iterator that computes values on-demand could not model ForwardIterator. That’s :’-(.

    It also means that iterators that return proxies — types that act like references — cannot be ForwardIterators. Hence, whether it was a good idea or not, std::vector<bool> is not a real container since its iterators return proxies.

    The new C++20 iterator concepts solve both of this problems with the help of std::ranges::iter_swap (a constrained version of std::iter_swap), and the new std::ranges::iter_move. Use ranges::iter_swap(i, j) to swap the values referred to by i and j. And use the following:

    iter_value_t<I> tmp = ranges::iter_move(i);
    

    … to move an element at position i out of sequence and into the temporary object tmp.

    Authors of proxy iterator types can hook these two customization points to make their iterators play nicely with the constrained algorithms in the std::ranges namespace (see below).

    The new iter_rvalue_reference_t<I> type alias mentioned above names the return type of ranges::iter_move(i).

    Contiguous Iterator Support

    In Stepanov’s STL, RandomAccessIterator is the strongest iterator category. But whether elements are contiguous in memory is a useful piece of information, and there exist algorithms that can take advantage of that information to become more efficient. Stepanov was aware of that but felt that raw pointers were the only interesting model of contiguous iterators, so he didn’t need to add a new category. He would have been appalled at the library vendors who ship std::vector implementations with wrapped debug iterators.

    TL;DR, we are now defining an extra category that subsumes (refines) RandomAccessIterator called ContiguousIterator. A type must opt-in to contiguity by defining a nested type named iterator_concept (note: not iterator_category) that is an alias for the new std::contiguous_iterator_tag tag type. Or you could specialize std::iterator_traits for your type and specify iterator_concept there.

    There is a whole blog post coming about iterator_category, iterator_concept, and how to write an iterator type that conforms both to the old iterator concepts and the new, with different strengths in each. It’s a brave new world of back-compat considerations.

    Constrained Algorithms

    Ever tried to pass a std::list‘s iterator to std::sort? Or any other combination of nonesense? When you accidentally fail to meet an algorithm’s (unstated) type requirements today, your compiler will inform you in the most obscure and voluminous way possible, spewing errors that appear to come from within the guts of your STL implementation.

    Concepts are designed to help with this. For instance, look at this code that is using the cmcstl2 reference implementation (which puts std::ranges in std::experimental::ranges for now):

    #include <list>
    #include <stl2/algorithm.hpp>
    using ranges = std::experimental::ranges;
    
    int main() {
      std::list<int> l {82,3,7,2,5,8,3,0,4,23,89};
      ranges::sort( l.begin(), l.end() );
    }
    

    Rather than an error deep in the guts of ranges::sort, the error message points right to the line in main that failed to meet the constraints of the sort template. “error: no matching call for ranges::sort(list<int>::iterator, list<int>::iterator)“, followed by a message that shows the prototype that failed to match and an explanation that the constraints within RandomAccessIterator we not satisfied. You can see the full error here.

    Much can be done to make the error more user-friendly, but it’s already a vast improvement over the status quo.

    Range Algorithms

    This one is fairly obvious. It’s been 20 years since the STL was standardized, and all I want to do is pass a vector to sort. Is that too much to ask? Nope. With C++20, you will finally be able to do this:

    std::vector< int > v =  // ...
    std::ranges::sort( v ); // Hurray!
    

    Constrained Function Objects

    Have you ever used std::less<>, the “diamond” specializations of the comparison function objects that were added in C++14? These let you compare things without having to say up front what type you’re comparing or forcing conversions. These exist in the std::ranges namespace too, but you don’t have to type <> because they are not templates. Also, they have constrained function call operators. So less, greater, less_equal, and greater_equal are all constrained with StrictTotallyOrderedWith, for instance.

    These types are particularly handy when defining APIs that accept a user-specified relation, but default the relation to operator< or operator==. For instance:

    template <class T, Relation<T, T> R = ranges::less>
    T max( T a, T b, R r = {} ) {
      return r( a, b ) ? b : a;
    }
    

    This function has the nice property that if the user specifies a relation, it will be used and the constraints guarantee that R is a Relation over type T. If the user doesn’t specify a relation, then the constraints require that T satisfies StrictTotallyOrderedWith itself. That is implicit in the fact that R defaults to ranges::less, and ranges::less::operator() is constrained with StrictTotallyOrderedWith.

    Generalized Callables

    In C++17, the Standard Library got a handy function: std::invoke. It lets you call any “Callable” thing with some arguments, where “Callable” includes ordinary function-like things in addition to pointers to members. However, the standard algorithms were not respecified to use std::invoke, which meant that code like the following failed to compile:

    struct Wizard {
      void frobnicate();
    };
    
    int main() {
      std::vector<Wizard> vw { /*...*/ };
      std::for_each( vw.begin(), vw.end(),
                     &Wizard::frobnicate ); // Nope!
    }
    

    std::for_each is expecting something callable like fun(t), not std::invoke(fun, t).

    The new algorithms in the std::ranges namespace are required to use std::invoke, so if the above code is changed to use std::ranges::for_each, it will work as written.

    Projections

    Ever wanted to sort a range of things by some property of those things? Maybe sort a vector of Employees by their ids? Or last name? Or maybe you want to seach an array of points for one where the magnitude is equal to a certain value. For those things, projections are very handy. A projection is a unary transformation function passed to an algorithm that gets applied to each element before the algorithm operates on the element.

    To take the example of sorting a vector of Employees by id, you can use a projection argument to std::ranges::sort as follows:

    struct Employee {
      int Id;
      std::string Name;
      Currency Salary;
    };
    
    int main() {
      using namespace std;
      vector<Employee> employees { /*...*/ };
      ranges::sort( employees, ranges::less{},
                    &Employee::Id );
    }
    

    The third argument to std::ranges::sort is the projection. Notice that we used a generalized callable for it, from the previous section. This sort command sorts the Employees by the Id field.

    Or for the example of searching an array of points for one where the magnitude is equal to a certain value, you would do the following:

    using namespace std;
    array< Point > points { /*...*/ };
    auto it = ranges::find( points, value, [](auto p) {
      return sqrt(p.x*p.x + p.y*p.y);
    } );
    

    Here we are using a projection to compute a property of each element and operating on the computed property.

    Once you get the hang of projections, you’ll find they have many uses.

    Range Utilities

    The part of the standard library shipping in the <ranges> header has a lot of goodies. Besides an initial set of lazy range adaptors (described below), it has some handy, general-purpose utilities.

    view_interface

    As in the Pythagorean triples example above, your custom view types can inhert from view_interface to get a host of useful member functions, like .front(), .back(), .empty(), .size(), .operator[], and even an explicit conversion to bool so that view types can be used in if statements:

    // Boolean conversion operator comes from view_interface:
    if ( auto evens = vec | view::filter(is_even) ) {
      // yup, we have some evens. Do something.
    }
    

    subrange

    std::ranges::subrange<I, S> is probably the most handy of the range utilities. It is an iterator/sentinel pair that models the View concept. You can use it to bundle together two iterators, or an iterator and a sentinel, for when you want to return a range or call an API that expects a range.

    It also has deduction guides that make it quite painless to use. Consider the following code:

    auto [b,e] = subrange{vec};
    

    This code is equivalent in effect to:

    auto b = ranges::begin(vec);
    auto e = ranges::end(vec);
    

    The expression subrange{vec} deduces the iterator and sentinel template parameters from the range vec, and since subrange is tuple-like, we can unpack the iterator/sentinel pair using structured bindings.

    ref_view

    Although not officially merged yet, C++20 will have a std::ranges::ref_view<R> which, like std::reference_wrapper is, well, a wrapper around a reference. In the case of ref_view, it is a reference to a range. It turns an lvalue container like std::vector<int>& into a View of the same elements that is cheap to copy: it simply wraps a pointer to the vector.

    Range Generators

    Now we get to the really fun stuff. The <ranges> header has a couple of ways to generate new ranges of values, including std::view::iota that we saw above. Here is how to use them, and what they mean:

    Syntax Semantics
    view::iota(i) Given the incrementable object i, generates an infinite range of values like [i,i+1,i+2,i+3,...).
    view::iota(i,j) Given the incrementable object i and some other object j that is comparable to i (but not necessarily the same type), generates a range of values like [i,i+1,i+2,i+3,...,j-1]. Note that the upper bound (j) is excluded, which makes this form usable with iterator/sentinel pairs. It can also be used to generate the indices of a range with view::iota(0u, ranges::size(rng)).
    view::single(x) Construct a one-element view of the value x; that is, [x].
    view::empty<T> A zero-element view of elements of type T.
    view::counted(it, n) Given an iterator it and a count n, constructs a finite range of n elements starting at the element denoted by it.

    Range Adaptors

    This is the really, really fun stuff. The true power of ranges lies in the ability to create pipelines that transform ranges on the fly. The range-v3 library has dozens of useful range adaptors. C++20 will only be getting a handful, but expect the set to grow over time.

    Syntax Semantics
    r | view::all Create a View over all the elements in Range r. Perhaps r is already a View. If not, turn it into one with ref_view if possible, or subrange failing that. Rvalue containers are not “viewable,” and so code like std::vector<int>{} | view::all will fail to compile.
    r | view::filter(pred) Given a viewable range r and a predicate pred, return a View that consists of all the elements e for which invoke(pred, e) returns true.
    r | view::transform(fn) Given a viewable range r and a function fn, return a View that consists of all the elements of r transformed with fn.
    r | view::reverse Given a viewable range r, return a View that iterates r‘s values in reverse order.
    r | view::take(n) Given a viewable range r, return a View containing the first n elements of r, or all the elements of r if r has fewer than n elements.
    r | view::join Given a viewable range of ranges, flatten all the ranges into a single range.
    r | view::split(r2) Given a viewable range r and a pattern range r2, return a View of Views where the inner ranges are delimited by r2. Alternativly, the delimiter can be a single value v which is treated as if it were view::single(v).
    r | view::common Given a viewable range r, return a View for which the begin and end iterators of the range have the same type. (Some ranges use a sentinel for the end position.) This range adaptor is useful primarily as a means of interfacing with older code (like the std:: algorithms) that expects begin and end to have the same type.

    These adaptors can be chained, so for instance, you can do the following:

    using namespace std;
    for ( auto && e : r | view::filter(pred)
                        | view::transform(fn) ) {
      // Iterate over filtered, transformed range
    }
    

    Of course, you can also use range adaptor pipelines as arguments to the range-based algorithms in std::ranges:

    using namespace std;
    // Insert a filtered, transformed range into
    // the back of container `v`.
    ranges::copy( r | view::filter(pred)
                    | view::transform(fn),
                  back_inserter(v) );
    

    Lazily adapting ranges is a powerful way to structure your programs. If you want a demonstration of how far this programming style can take you, see my CppCon keynote on ranges from 2015, or just skim the code of the calendar application I describe there, and note the lack of loops, branches, and overt state manipulation. ‘Nuf said.

    Future Directions

    Clearly, C++20 is getting a lot of new functionality in support of ranges. Getting here has taken a long time, mostly because nobody had ever built a fully general, industrial strength, generic library using the C++20 language support for concepts before. But now we are over that hump. All the foundational pieces are in place, and we’ve acrued a lot of knowledge in the process. Expect the feature set to expand rapidly post-C++20. There are already papers in flight.

    Things currently in the works include:

    • Constructors for the standard containers that accept ranges,
    • A take_while range adaptor that accepts a predicate and returns a view of the first N elements for which the predicate evaluates to true,
    • A drop range adaptor that returns a view after dropping the first N elements of the input range,
    • A drop_while view that drops elements from an input range that satisfy a predicate.
    • An istream_view that is parameterized on a type and that reads elements of that type from a standard istream,
    • A zip view that takes N ranges and produces a view where the elements are N-tuples of the elements of the input ranges, and
    • A zip_with view that takes N ranges and a N-ary function, and produces a view where the elements are the result of calling the function with the elements of the input ranges.

    And there’s more, lots more in range-v3 that has proven useful and will eventually be proposed by myself or some other interested range-r. Things I would especially like to see:

    • An iterator faรงade class template like range-v3’s basic_iterator;
    • A view faรงade class template like range-v3’s view_facade;
    • Range-ified versions of the numeric algorithms (e.g., accumulate, partial_sum, inner_product);
    • More range generators and adaptors, like view::chunk, view::concat, view::group_by, view::cycle, view::slice, view::stride, view::generate[_n], view::repeat[_n], a view::join that takes a delimiter, view::intersperse, view::unique, and view::cartesian_product, to name the more important ones; and
    • A “complete” set of actions to go along with the views. Actions, like the adaptors in the view:: namespace, operate on ranges and compose into pipelines, but actions act eagerly on whole containers, and they are potentially mutating. (The views are non-mutating.)

    With actions, it should be possible to do:

    v = move(v) | action::sort | action::unique;
    

    …to sort a vector and remove all duplicate elements.

    And I haven’t even mentioned asynchronous ranges yet. But that’s a whole other blog post. ๐Ÿ™‚

    Summary

    C++20 is rapidly approaching, and now that the Ranges work has been officially merged into the working draft, I have been hearing from Standard Library vendors who are starting to think about implementing all of this. Only GCC is in a position to ship the ranges support any time soon, since it is the only compiler currently shipping with support for concepts. But clang has a concepts branch which is already usable, so there is hope for concepts — and ranges — in clang trunk sometime in the not-too-distant future. And Microsoft has publicly committed to supporting all of C++20 including concepts and ranges, and the conformance of the Microsoft compiler has been rapidly improving, recently gaining the ability to compile range-v3. So things are looking good there, too.

    It’s a stRANGE new world. Thanks for reading.

    "\e"
  • Ranges, Coroutines, and React: Early Musings on the Future of Async in C++

    Disclaimer: these are my early thoughts. None of this is battle ready. Youโ€™ve been warned.

    Hello, Coroutines!

    At the recent C++ Committee meeting in Toronto, the Coroutines TS was forwarded to ISO for publication. That roughly means that the coroutine โ€œfeature branchโ€ is finished, and is ready to be merged into trunk (standard C++) after a suitable vetting period (no less than a year). That puts it on target for C++20. What does that mean for idiomatic modern C++?

    Lots, actually. With the resumable functions (aka, stackless coroutines) from the Coroutines TS, we can do away with callbacks, event loops, and future chaining (future.then()) in our asynchronous APIs. Instead, our APIs can return โ€œawaitableโ€ types. Programmers can then just use these APIs in a synchronous-looking style, spamming co_await in front of any async API call and returning an awaitable type.

    This is a bit abstract, so this blog post make it more concrete. It describes how the author wrapped the interface of libuv — a C library that provides the asynchronous I/O in Node.js — in awaitables. In libuv, all async APIs take a callback and loop on an internal event loop, invoking the callback when the operation completes. Wrapping the interfaces in awaitables makes for a much better experience without the callbacks and the inversion of control they bring.

    Below, for instance, is a function that (asynchronously) opens a file, reads from it, writes it to stdout, and closes it:

    auto start_dump_file( const std::string& str )
      -> future_t<void>
    {
      // We can use the same request object for
      // all file operations as they don't overlap.
      static_buf_t<1024> buffer;
    
      fs_t openreq;
      uv_file file = co_await fs_open(uv_default_loop(),
                                      &openreq,
                                      str.c_str(),
                                      O_RDONLY,
                                      0);
      if (file > 0)
      {
        while (1)
        {
          fs_t readreq;
          int result = co_await fs_read(uv_default_loop(),
                                        &readreq,
                                        file,
                                        &buffer,
                                        1,
                                        -1);
          if (result <= 0)
            break;
          buffer.len = result;
          fs_t req;
          (void) co_await fs_write(uv_default_loop(),
                                   &req,
                                   1 /*stdout*/,
                                   &buffer,
                                   1,
                                   -1);
        }
        fs_t closereq;
        (void) co_await fs_close(uv_default_loop(),
                                 &closereq,
                                 file);
      }
    }
    

    You can see that this looks almost exactly like ordinary synchronous code, with two exceptions:

    1. Calls to asynchronous operations are preceded with co_await, and
    2. The function returns an awaitable type (future_t<void>).

    Very nice. But this code snippet does too much in my opinion. Wouldnโ€™t it be nice to have a reusable component for asynchronously reading a file, separate from the bit about writing it to stdout? What would that even look like?

    Hello, Ranges!

    Also at the recent C++ Committee meeting in Toronto, the Ranges TS was forwarded to ISO for publication. This is the first baby step toward a complete reimagining and reimplementation of the C++ standard library in which interfaces are specified in terms of ranges in addition to iterators.

    Once we have “range” as an abstraction, we can build range adaptors and build pipelines that transform ranges of values in interesting ways. More than just a curiosity, this is a very functional style that lets you program without a lot of state manipulation. The fewer states your program can be in, the easier it is for you to reason about your code, and the fewer bugs youโ€™ll have. (For more on that, you can see my 2015 C++Con talk about ranges; or just look at the source for a simple app that prints a formatted calendar to stdout, and note the lack of loops, conditionals, and overt state manipulation.)

    For instance, if we have a range of characters, we might want to lazily convert each character to lowercase. Using the range-v3 library, you can do the following:

    std::string hello("Hello, World!");
    using namespace ranges;
    auto lower = hello
               | view::transform([](char c){
                   return (char)std::tolower(c);});
    

    Now lower presents a view of hello where each character is run through the tolower transform on the fly.

    Although the range adaptors havenโ€™t been standardized yet, the Committee has already put its stamp of approval on the overall direction, including adaptors and pipelines. (See N4128 for the ranges position paper.) Someday, these components will all be standard, and the C++ community can encourage their use in idiomatic modern C++.

    Ranges + Coroutines == ?

    With coroutines, ranges become even more powerful. For one thing, the co_yield keyword makes it trivial to define your own (synchronous) ranges. Already with range-v3 you can use the following code to define a range of all the integers and apply a filter to them:

    #include <iostream>
    #include <range/v3/all.hpp>
    #include <range/v3/experimental/utility/generator.hpp>
    
    using namespace ranges;
    
    // Define a range of all the unsigned shorts:
    experimental::generator<unsigned short> ushorts()
    {
      unsigned short u = 0;
      do { co_yield u; } while (++u);
    }
    
    int main()
    {
      // Filter all the even unsigned shorts:
      auto evens = ushorts()
                 | view::filter([](auto i) {
                       return (i % 2) == 0; });
    
      // Write the evens to cout:
      copy( evens, ostream_iterator<>(std::cout, "\n") );
    }
    

    Put the above code in a .cpp file, compile with a recent clang and -fcoroutines-ts -std=gnu++1z, and away you go. Congrats, youโ€™re using coroutines and ranges together. This is a trivial example, but you get the idea.

    Asynchronous Ranges

    That great and all, but itโ€™s not asynchronous, so who cares? If it were asynchronous, what would that look like? Moving to the first element of the range would be an awaitable operation, and then moving to every subsequent element would also be awaitable.

    In the ranges world, moving to the first element of a range R is spelled โ€œauto it = begin(R)โ€, and moving to subsequent elements is spelled โ€œ++itโ€. So for an asynchronous range, those two operations should be awaitable. In other words, given an asynchronous range R, we should be able to do:

    // Consume a range asynchronously
    for( auto it = co_await begin(R);
         it != end(R);
         co_await ++it )
    {
      auto && e = *it;
      do_something( e );
    }
    

    In fact, the Coroutines TS anticipates this and has a asynchronous range-based for loop for just this abstraction. The above code can be rewritten:

    // Same as above:
    for co_await ( auto&& e : R )
    {
      do_something( e );
    }
    

    Now we have two different but closely related abstractions: Range and AsynchronousRange. In the first, begin returns something that models an Iterator. In the second, begin returns an Awaitable of an AsynchronousIterator. What does that buy us?

    Asynchronous Range Adaptors

    Once we have an abstraction, we can program against that abstraction. Today we have a view::transform that knows how to operate on synchronous ranges. It can be extended to also work with asynchronous ranges. So can all the other range adaptors: filter, join, chunk, group_by, interleave, transpose, etc, etc. So it will be possible to build a pipeline of operations, and apply the pipeline to a synchronous range to get a (lazy) synchronous transformation, and apply the same exact pipeline to an asynchronous range to get a non-blocking asynchronous transformation. The benefits are:

    • The same functional style can be used for synchronous and asynchronous code, reusing the same components and the same idioms.
    • Asynchronous code, when expressed with ranges and transformations, can be made largely stateless, as can be done today with synchronous range-based code. This leads to programs with fewer states and hence fewer state-related bugs.
    • Range-based code composes very well and encourages a decomposition of problems into orthogonal pieces which are easily testable in isolation. (E.g., a view::filter component can be used with any input range, synchronous or asynchronous, and can be easily tested in isolation of any particular range.)

    Another way to look at this is that synchronous ranges are an example of a pull-based interface: the user extracts elements from the range and processes them one at a time. Asynchronous ranges, on the other hand, represent more of a push-based model: things happen when data shows up, whenever that may be. This is akin to the reactive style of programming.

    By using ranges and coroutines together, we unify push and pull based idioms into a consistent, functional style of programming. And thatโ€™s going to be important, I think.

    Back to LibUV

    Earlier, we wondered about a reusable libuv component that used its asynchronous operations to read a file. Now we know what such a component could look like: an asynchronous range. Letโ€™s start with an asynchronous range of characters. (Here Iโ€™m glossing over the fact that libuv deals with UTF-8, not ASCII. Iโ€™m also ignoring errors, which is another can of worms.)

    auto async_file( const std::string& str )
      -> async_generator<char>
    {
      // We can use the same request object for
      // all file operations as they don't overlap.
      static_buf_t<1024> buffer;
    
      fs_t openreq;
      uv_file file = co_await fs_open(uv_default_loop(),
                                      &openreq,
                                      str.c_str(),
                                      O_RDONLY,
                                      0);
      if (file > 0)
      {
        while (1)
        {
          fs_t readreq;
          int result = co_await fs_read(uv_default_loop(),
                                        &readreq,
                                        file,
                                        &buffer,
                                        1,
                                        -1);
          if (result <= 0)
            break;
          // Yield the characters one at a time.
          for ( int i = 0; i < result; ++i )
          {
            co_yield buffer.buffer[i];
          }
        }
        fs_t closereq;
        (void) co_await fs_close(uv_default_loop(),
                                 &closereq,
                                 file);
      }
    }
    

    The async_file function above asynchronously reads a block of text from the file and then co_yields the individual characters one at a time. The result is an asynchronous range of characters: async_generator<char>. (For an implementation of async_generator, look in Lewis Bakerโ€™s cppcoro library.)

    Now that we have an asynchronous range of characters representing the file, we can apply transformations to it. For instance, we could convert all the characters to lowercase:

    // Create an asynchronous range of characters read
    // from a file and lower-cased:
    auto async_lower = async_file("some_input.txt")
                     | view::transform([](char c){
                         return (char)std::tolower(c);});
    

    Thatโ€™s the same transformation we applied above to a std::string synchronously, but here it’s used asynchronously. Such an asynchronous range can then be passed through further transforms, asynchronously written out, or passed to an asynchronous std:: algorithm (because weโ€™ll need those, too!)

    One More Thing

    I hear you saying, โ€œProcessing a file one character at a time like this would be too slow! I want to operate on chunks.โ€ The above async_file function is still doing too much. It should be an asynchronous range of chunks. Letโ€™s try again:

    auto async_file_chunk( const std::string& str )
      -> async_generator<static_buf_t<1024>&>
    {
      // We can use the same request object for
      // all file operations as they don't overlap.
      static_buf_t<1024> buffer;
    
      fs_t openreq;
      uv_file file = co_await fs_open(uv_default_loop(),
                                      &openreq,
                                      str.c_str(),
                                      O_RDONLY,
                                      0);
      if (file > 0)
      {
        while (1)
        {
          fs_t readreq;
          int result = co_await fs_read(uv_default_loop(),
                                        &readreq,
                                        file,
                                        &buffer,
                                        1,
                                        -1);
          if (result <= 0)
            break;
          // Just yield the buffer.
          buffer.len = result;
          co_yield buffer;
        }
        fs_t closereq;
        (void) co_await fs_close(uv_default_loop(),
                                 &closereq,
                                 file);
      }
    }
    

    Now if I want to, I can asynchronously read a block and asynchronously write the block, as the original code was doing, but while keeping those components separate, as they should be.

    For some uses, a flattened view would be more convenient. No problem. Thatโ€™s what the adaptors are for. If static_buf_t is a (synchronous) range of characters, we already have the tools we need:

    // Create an asynchronous range of characters read from a
    // chunked file and lower-cased:
    auto async_lower = async_file_chunk("some_input.txt")
                     | view::join
                     | view::transform([](char c){
                         return (char)std::tolower(c);});
    

    Notice the addition of view::join. Its job is to take a range of ranges and flatten it. Letโ€™s see what joining an asynchronous range might look like:

    template <class AsyncRange>
    auto async_join( AsyncRange&& rng )
      -> async_generator<range_value_t<
           async_range_value_t<AsyncRange>>>
    {
      for co_await ( auto&& chunk : rng )
      {
        for ( auto&& e : chunk )
          co_yield e;
      }
    }
    

    We (asynchronously) loop over the outer range, then (synchronously) loop over the inner ranges, and co_yield each value. Pretty easy. From there, itโ€™s just a matter of rigging up operator| to async_join to make joining work in pipelines. (A fully generic view::join will be more complicated than that since both the inner and outer ranges can be either synchronous or asynchronous, but this suffices for now.)

    Summary

    With ranges and coroutines together, we can unify the push and pull programming idioms, bringing ordinary C++ and reactive C++ closer together. The C++ Standard Library is already evolving in this direction, and I’m working to make that happen both on the Committee and internally at Facebook.

    Thereโ€™s LOTS of open questions. How well does this perform at runtime? Does this scale? Is it flexible enough to handle lots of interesting use cases? How do we handle errors in the middle of an asynchronous pipeline? What about splits and joins in the async call graph? Can this handle streaming interfaces? And so on. Iโ€™ll be looking into all this, but at least for now I have a promising direction, and thatโ€™s fun.

    "\e"
  • Post-Conditions on Self-Move

    UPDATE April 8, 2016 This post has been edited since publication to reflect my evolving understanding. As a result of the issues raised in this post, it’s possible that the committee decides to strengthen the post-conditions on move, so the recommendations made here may evolve further. Stay tuned.

    TL;DR: In addition to the usual rule about move operations leaving the source object in a valid but unspecified state, we can add an additional rule:

    Self-move assignment should โ€œworkโ€ and at the very least leave the object in a valid but unspecified state.

    Discussion

    What do you think the following code should do?

    X x = {/*something*/};
    x = std::move(x);
    

    Yes, itโ€™s dumb, but with our alias-happy language, it can happen. So what does the standard say about this? For that we turn to [res.on.arguments]/p1.3 taken from the library introduction (emphasis mine):

    If a function argument binds to an rvalue reference parameter, the implementation may assume that this parameter is a unique reference to this argument. […] If a program casts an lvalue to an xvalue while passing that lvalue to a library function (e.g. by calling the function with the argument std::move(x)), the program is effectively asking that function to treat that lvalue as a temporary. The implementation is free to optimize away aliasing checks which might be needed if the argument waswere an lvalue.

    (I fixed the grammar mistake because I am a Huge Dork.) The above seems to say that std::swap(x, x) is playing with fire, because std::swap is implemented as follows:

    template <class T>
    void swap(T& a, T& b) {
      auto x(std::move(a));
      a = std::move(b); // Here be dragons
      b = std::move(x);
    }
    

    If a and b refer to the same object, the second line of std::swap does a self-move assign. Blamo! Undefined behavior, right?

    Such was what I thought when I first wrote this post until Howard Hinnant drew my attention to the requirements table for the MoveAssignable concept, which says that for the expression t = rv (emphasis mine):

    If t and rv do not refer to the same object, t is equivalent to the value of rv before the assignment […] rvโ€™s state is unspecified. [ Note: rv must still meet the requirements of the library component that is using it, whether or not t and rv refer to the same object. […] –end note]

    Ah, ha! So here we have it. After a self-move, the object is required to be in a valid-but-unspecified state.

    My attention we drawn to this issue during a code review of a change I wanted to make to Folly‘s Function class template. I wanted to change this:

    Function& operator=(Function&& that) noexcept {
      if (this != &that) {
        // do the move
      }
      return *this;
    }
    

    to this:

    Function& operator=(Function&& that) noexcept {
      assert(this != &that);
      // do the move
      return *this;
    }
    

    The reason: letโ€™s make moves as fast as possible and take advantage of the fact that Self-Moves Shouldnโ€™t Happen. We assert, fix up the places that get it wrong, and make our programs an iota faster. Right?

    Not so fast, said one clued-in reviewer. Self-swaps can happen quite easily in generic algorithms, and they shouldnโ€™t trash the state of the object or the state of the program. This rang true, and so begin my investigation.

    A few Google searches later turned up this StackOverflow gem from Howard Hinnant. C++ wonks know Howard Hinnant. Heโ€™s the author of libc++, and an old time C++ library developer. (Remember Metrowerks CodeWarrior? No? Get off my lawn.) He also happens to be the person who wrote the proposal to add rvalue references to the language, so you know, Howardโ€™s given this some thought. First Howard says this:

    Some will argue that swap(x, x) is a good idea, or just a necessary evil. And this, if the swap goes to the default swap, can cause a self-move-assignment.

    I disagree that swap(x, x) is ever a good idea. If found in my own code, I will consider it a performance bug and fix it.

    But then in an Update, he backtracks:

    I’ve given this issue some more thought, and changed my position somewhat. I now believe that assignment should be tolerant of self assignment, but that the post conditions on copy assignment and move assignment are different:

    For copy assignment:

    x = y;
    

    one should have a post-condition that the value of y should not be altered. When &x == &y then this postcondition translates into: self copy assignment should have no impact on the value of x.

    For move assignment:

    x = std::move(y);
    

    one should have a post-condition that y has a valid but unspecified state. When &x == &y then this postcondition translates into: x has a valid but unspecified state. I.e. self move assignment does not have to be a no-op. But it should not crash. This post-condition is consistent with allowing swap(x, x) to just work […]

    When Howard Hinnant changes his mind about something having to do with library design, I sit up and take note, because it means that something very deep and subtle is going on. In this case, it means Iโ€™ve been writing bad move assignment operators for years.

    By Howardโ€™s yardstick — and by the requirements for the MoveAssignable concept in the standard, thanks Howard! — this move assignment operator is wrong:

    Function& operator=(Function&& that) noexcept {
      assert(this != &that); // No! Bad C++ programmer!
      // do the move
      return *this;
    }
    

    Move assignment operators should accept self-moves and do no evil; indeed for std::swap(f, f) to work it must.

    Thatโ€™s not the same as saying it needs to preserve the objectโ€™s value, though, and not preserving the objectโ€™s value can be a performance win. It can save a branch, for instance. Here is how I reformulated folly::Functionโ€™s move assignment operator[*]:

    Function& operator=(Function&& that) noexcept {
      clear_();        // Free all of the resources owned by *this
      moveFrom_(that); // Move that's guts into *this.
      return *this;
    }
    

    [*] Well, not exactly, but thatโ€™s the gist.

    Of note is that clear_() leaves *this in a state such that it is still OK to moveFrom_(*this), which is what happens when that and *this are the same object. In the case of Function, it just so happens that the effect of this code is to put the Function object back into the default-constructed state, obliterating the previous value. The particular final state of the object isnโ€™t important though, so long as it is still valid.

    Summary

    So, as always we have the rule about moves:

    Move operations should leave the source object in a valid but unspecified state.

    And to that we can add an additional rule:

    Self-moves should do no evil and leave the object in a valid but unspecified state.

    If you want to go further and leave the object unmodified, that’s not wrong per se, but itโ€™s not required by the standard as it is today. Changing the value is perfectly OK (Howard and the standard say so!), and doing that might save you some cycles.

    TIL

    "\e"
  • Iterators++, Part 3

    This is the fourth and final post in a series about proxy iterators, the limitations of the existing STL iterator concept hierarchy, and what could be done about it. The first three posts describe the problems of proxy iterators, the way to swap and move their elements, and how to rigorously define what an Iterator is.

    This time around I’ll be focusing on the final problem: how to properly constrain the higher-order algorithms so that they work with proxy iterators.

    A Unique Algorithm

    In this post, I’ll be looking at one algorithm in particular and how it interacts with proxy iterators: unique_copy. Here is its prototype:

    template <class InIter, class OutIter, class Fn>
    OutIter unique_copy(InIter first, InIter last,
                        OutIter result, Fn binary_pred);
    

    This algorithm copies elements from one range to another, skipping adjacent elements that are equal, using a predicate for the comparison.

    Consider the following invocation:

    std::stringstream sin{"1 1 2 3 3 3 4 5"};
    unique_copy(
      std::istream_iterator<int>{sin},
      std::istream_iterator<int>{},
      std::ostream_iterator<int>{std::cout, " "},
      std::equal_to<int>{} );
    

    This reads a bunch of ints from sin and writes the unique ones to cout. Simple, right? This code prints:

    1 2 3 4 5
    

    Think for a minute how you would implement unique_copy. First you read an int from the stream. Then you write it out to the other stream. Then you read another int. You want to compare it to the last one. Ah! You need to save the last element locally so that you can do the comparisons. Interesting.

    When I really want to understand how some part of the STL works, I check out how the feature is implemented in ye olde SGI STL. This codebase is so old, it may have first been written on parchment and compiled by monks. But it’s the cleanest and most straightforward STL implementation I know, and I recommend reading it through. Here, modulo some edits for readability, is the relevant part of unique_copy:

    // Copyright (c) 1994
    // Hewlett-Packard Company
    // Copyright (c) 1996
    // Silicon Graphics Computer Systems, Inc.
    template <class InIter, class OutIter, class Fn,
              class _Tp>
    OutIter
    __unique_copy(InIter first, InIter last,
                  OutIter result,
                  Fn binary_pred, _Tp*) {
      _Tp value = *first;
      *result = value;
      while (++first != last)
        if (!binary_pred(value, *first)) {
          value = *first;
          *++result = value;
        }
      return ++result;
    }
    

    (The calling code ensures that first != last, which explains why this code skips that check. And the strange _Tp* argument is so that the iterator’s value type can be deduced; the monks couldn’t compile traits classes.) Note the value local variable on line 11, and especially note line 14, where it passes a value and a reference to binary_pred. Keep that in mind because it’s important!

    The Plot Thickens

    You probably know more about unique_copy now than you ever cared to. Why do I bring it up? Because it’s super problematic when used with proxy iterators. Think about what happens when you try to pass vector<bool>::iterator to the above __unique_copy function:

    std::vector<bool> vb{true, true, false, false};
    using R = std::vector<bool>::reference;
    __unique_copy(
      vb.begin(), vb.end(),
      std::ostream_iterator<bool>{std::cout, " "},
      [](R b1, R b2) { return b1 == b2; }, (bool*)0 );
    

    This should write a “true” and a “false” to cout, but it doesn’t compile. Why? The lambda is expecting to be passed two objects of vector<bool>‘s proxy reference type, but remember how __unique_copy calls the predicate:

    if (!binary_pred(value, *first)) { /*...*/
    

    That’s a bool& and a vector<bool>::reference. Ouch!

    They’re just bools, and bools are cheap to copy, so take them by value. Problem solved. Well, sure, but what if they weren’t bools? What if we proxied a sequence of things that are expensive to copy? Now the problem is harder.

    So for lack of anything better (and pretending that bools are expensive to copy, bear with me), you write the lambda like this:

    [](bool& b1, R b2) { return b1 == b2; }
    

    Yuk. Now you port this code to another STL that happens to call the predicate with reversed arguments and the code breaks again. ๐Ÿ™

    My point is this: once we introduce proxy iterators into the mix, it becomes non-obvious how to define predicates for use with the algorithms. Sometimes the algorithms call the predicates with references, sometimes with values, and sometimes — like unique_copy — with a mix of both. Algorithms like sort first call the predicate one way, and then later call it another way. Vive la diffรฉrence!

    A Common Fix

    This problem has a very simple solution in C++14: a generic lambda. We can write the above code simply, portably, and optimally as follows:

    std::vector<bool> vb{true, true, false, false};
    std::unique_copy(
      vb.begin(), vb.end(),
      std::ostream_iterator<bool>{std::cout, " "},
      [](auto&& b1, auto&& b2) { return b1 == b2; } );
    

    No matter what unique_copy throws at this predicate, it will accommodate it with grace and style.

    But still. Polymorphic function objects feel like a big hammer. Some designs require monomorphic functions, like std::function or virtuals, or maybe even a function pointer if you have to interface with C. My point is, it feels wrong for the STL to require the use of a polymorphic function for correctness.

    To restate the problem, we don’t know how to write a monomorphic predicate for unique_copy when our sequence is proxied because value_type& may not convert to reference, and reference may not convert to value_type&. If only there were some other type, some other reference-like type, they could both convert to…

    But there is! If you read my last post, you know about common_reference, a trait that computes a reference-like type (possibly a proxy) to which two other references can bind (or convert). In order for a proxy iterator to model the Iterator concept, I required that an iterator’s reference type and its value_type& must share a common reference. At the time, I insinuated that the only use for such a type is to satisfy the concept-checking machinery. But there’s another use for it: the common reference is the type we could use to define our monomorphic predicate.

    I can imagine a future STL providing the following trait:

    // An iterator's common reference type:
    template <InputIterator I>
    using iterator_common_reference_t =
      common_reference_t<
        typename iterator_traits<I>::value_type &
        typename iterator_traits<I>::reference>;
    

    We could use that trait to write the predicate as follows:

    using I = vector<bool>::iterator;
    using C = iterator_common_reference_t<I>;
    auto binary_pred = [](C r1, C r2) {
      return r1 == r2;
    };
    

    That’s certainly a fair bit of hoop-jumping just to define a predicate. But it’s not some new complexity that I’m introducing. unique_copy and vector<bool> have been there since 1998. I’m just trying to make them play nice.

    And these hoops almost never need to be jumped. You’ll only need to use the common reference type when all of the following are true: (a) you are dealing with a proxied sequence (or are writing generic code that could deal with proxied sequences), (b) taking the arguments by value is undesirable, and (c) using a polymorphic function is impossible or impractical for some reason. I wouldn’t think that’s very often.

    Algorithm Constraints

    So that’s how things look from the perspective of the end user. How do they look from the other side, from the perspective of the algorithm author? In particular, how should unique_copy look once we use Concepts Lite to constrain the algorithm?

    The Palo Alto TR takes a stab at it. Here is how it constrains unique_copy:

    template <InputIterator I, WeaklyIncrementable Out,
              Semiregular R>
    requires Relation<R, ValueType<I>, ValueType<I>> &&
             IndirectlyCopyable<I, Out>
    Out unique_copy(I first, I last, Out result, R comp);
    

    There’s a lot going on there, but the relevant part is Relation<R, ValueType<I>, ValueType<I>>. In other words, the type R must be an equivalence relation that accepts arguments of the range’s value type. For all the reasons we’ve discussed, that doesn’t work when dealing with a proxied range like vector<bool>.

    So what should the constraint be? Maybe it should be Relation<R, ValueType<I>, Reference<I>>? But no, unique_copy doesn’t always need to copy a value into a local. Only when neither the input nor the output iterators model ForwardIterator. So sometimes the unique_copy calls the predicate like pred(*i,*j) and sometimes like pred(value, *i). The constraint has to be general enough to accommodate that.

    Maybe it could also use the iterator’s common reference type? What if we constrained unique_copy like this:

    template <InputIterator I, WeaklyIncrementable Out,
              Semiregular R>
    requires Relation<R, CommonReferenceType<I>,
                         CommonReferenceType<I>> &&
             IndirectlyCopyable<I, Out>
    Out unique_copy(I first, I last, Out result, R comp);
    

    This constraint make a promise to callers: “I will only pass objects of type CommonReferenceType<I> to the predicate.” But that’s a lie. It’s not how unique_copy is actually implemented. We could change the implementation to fulfill this promise by casting the arguments before passing them to the predicate, but that’s ugly and potentially inefficient.

    Really, I think we have to check that the predicate is callable with all the possible combinations of values and references. That sucks, but I don’t see a better option. With some pruning, these are the checks that I think matter enough to be required:

    Relation<R, ValueType<I>, ValueType<I>> &&
    Relation<R, ValueType<I>, ReferenceType<I>> &&
    Relation<R, ReferenceType<I>, ValueType<I>> &&
    Relation<R, ReferenceType<I>, ReferenceType<I>> &&
    Relation<R, CommonReferenceType<I>, CommonReferenceType<I>>
    

    As an implementer, I don’t want to write all that, and our users don’t want to read it, so we can bundle it up nice and neat:

    IndirectRelation<R, I, I>
    

    That’s easier on the eyes and on the brain.

    Interesting Indirect Invokable Implications

    In short, I think that everywhere the algorithms take a function, predicate, or relation, we should add a constraint like IndirectFunction, IndirectPredicate, or IndirectRelation. These concepts will require that the function is callable with a cross-product of values and references, with an extra requirement that the function is also callable with arguments of the common reference type.

    This might seem very strict, but for non-proxy iterators, it adds exactly zero new requirements. And even for proxy iterators, it’s only saying in code the things that necessarily had to be true anyway. Rather than making things harder, the common reference type makes them easier: if your predicate takes arguments by the common reference type, all the checks succeed, guaranteed.

    It’s possible that the common reference type is inefficient to use. For instance, the common reference type between bool& and vector<bool>::reference is likely to be a variant type. In that case, you might not want your predicate to take arguments by the common reference. Instead, you’d want to use a generic lambda, or define a function object with the necessary overloads. The concept checking will tell you if you forgot any overloads, ensuring that your code is correct and portable.

    Summary

    That’s the theory. I implemented all this in my Range-v3 library. Now I can sort a zip range of unique_ptrs. So cool.

    Here, in short, are the changes we would need to make the STL fully support proxy iterators:

    1. The algorithms need to use iter_swap consistently whenever elements need to be swapped. iter_swap should be a documented customization point.
    2. We need an iter_move customization point so that elements can be moved out of and back into sequence. This gives iterators a new rvalue_reference associated type.
    3. We need a new common_reference trait that, like common_type, can be specialized on user-defined types.
    4. All iterators need to guarantee that their value_type and reference associated types share a common reference. Likewise for value_type/rvalue_reference, and for reference/rvalue_reference.
    5. We need IndirectFunction, IndirectPredicate, and IndirectRelation concepts as described above. The higher-order algorithms should be constrained with them.

    From the end users’ perspective, not a lot changes. All existing code works as it did before, and all iterators that are valid today continue being valid in the future. Some proxy iterators, like vector<bool>‘s, would need some small changes to model the Iterator concept, but afterward those iterators are on equal footing with all the other iterators for the first time ever. Code that deals with proxy sequences might need to use common_reference when defining predicates, or they might need to use a generic lambda instead.

    So that’s it. To the best of my knowledge, this is the first comprehensive solution to the proxy iterator problem, a problem we’ve lived with from day one, and which only promises to get worse with the introduction of range views. There’s some complexity for sure, but the complexity seems to be necessary and inherent. And honestly I don’t think it’s all that bad.

    Future Directions

    I’m unsure where this goes from here. I plan to sit on it for a bit to see if any better solutions come along. There’s been some murmuring about a possible language solution for proxy references, but there is inherent complexity to proxy iterators, and it’s not clear to me at this point how a language solution would help.

    I’m currently working on what I believe will be the first draft of a Ranges TS. That paper will not address the proxy iterator problem. I could imagine writing a future paper that proposes the changes I suggest above. Before I do that, I would probably try to start a discussion on the committee mailing lists to feel people out. If any committee members are reading this, feel free to comment below.

    Thanks for following along, and thanks for all your encouraging and thought-provoking comments. Things in the C++ world are moving fast these days. It’s tough to keep up with it all. I feel blessed that you all have invested so much time exploring these issues with me. <3

    As always, you can find all code described here in my range-v3 repo on github.

    "\e"
  • Iterators++, Part 2

    Disclaimer: This is a long, boring post about minutia. For serious library wonks only.

    This is the third in a series about proxy iterators, the limitations of the existing STL iterator concept hierarchy, and what could be done about it. In the first post I explained what proxy iterators are (an iterator like vector<bool>‘s that, when dereferenced, returns a proxy object rather than a real reference) and three specific difficulties they cause in today’s STL:

    1. What, if anything, can we say in general about the relationship between an iterator’s value type and its reference type?
    2. How do we constrain higher-order algorithms like for_each and find_if that take functions that operate on a sequence’s elements?
    3. How do we implement algorithms that must swap and move elements around, like sort and reverse?

    In the second post, I zoomed in on the problem (3) and showed how the existing std::iter_swap API could be pressed into service, along with a new API that I propose: std::iter_move. Together, these APIs give an iterator a channel through which to communicate to the algorithms how its elements should be swapped and moved. With the addition of the iter_move API, iterators pick up a new associated type: rvalue_reference, which can live in std::iterator_traits alongside the existing value_type and reference associated types.

    In this post, I’ll dig into the first problem: how we define in code what an iterator is.

    Values and References

    As in the first two articles, I’ll use the zip view to motivate the discussion, because it’s easy to grok and yet totally bedeviling for the STL algorithms. Recall that zip lazily adapts two sequences by making them look like one sequence of pairs, as demonstrated below:

    std::vector<int> x{1,2,3,4};
    std::vector<int> y{9,8,7,6};
    
    using namespace ranges;
    auto zipped = view::zip(x, y);
    
    assert(*zipped.begin() == std::make_pair(1,9));
    assert(&(*zipped.begin()).first == &x[0]);
    

    As the two assertions above show, dereferencing a zip iterator yields a pair, and that the pair is actually a pair of references, pointing into the underlying sequences. The zip range above has the following associated types:

    Associated type… … for the zip view
    value_type pair<int, int>
    reference pair<int &, int &>
    rvalue_reference pair<int &&, int &&>

    With Concepts coming to C++, we’re going to need to say in code what an iterator is. The Palo Alto TR, published in 2012, takes a stab at it: an InputIterator is Readable and Incrementable, where Readable is defined as follows:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            { *i } -> const ValueType<I> &;
        };
    

    This says that a Readable type has an associated ValueType. It also says that *i is a valid expression, and that the result of *i must be convertible to const ValueType<I> &. This is fine when *i returns something simple like a real reference. But when it returns a proxy reference, like the zip view does, it causes problems.

    Substituting a zip iterator into the requires clause above results in something like this:

    const pair<int,int>& x = *i;
    

    This tries to initialize x with a pair<int&, int&>. This actually works in a sense; the temporary pair<int &, int &> object is implicitly converted into a temporary pair<int, int> by copying the underlying integers, and that new pair is bound to the const & because temporaries can bind to const references.

    But copying values is not what we want or expect. If instead of ints, we had pairs of some move-only type like unique_ptr, this wouldn’t have worked at all.

    So the Readable concept needs to be tweaked to handle proxy references. What can we do?

    One simple way to make the zip iterator model the Readable concept is to simply remove the requirement that *i be convertible to const ValueType<I>&. This is unsatisfying. Surely there is something we can say about the relationship between an iterator’s reference type and its value type. I think there is, and there’s a hint in the way the Palo Alto TR defines the EqualityComparable constraint.

    Common Type Constraints

    What do you think about code like this?

    vector<string> strs{"three", "blind", "mice"};
    auto it = find(strs.begin(), strs.end(), "mice");
    

    Seems reasonable, right? This searches a range of string‘s for a char const*. This should this work, even though it’s looking for an orange in a bucket of apples. The orange is sufficiently apple-like, and because we know how to compare apples and oranges; i.e., there is an operator== that compares strings with char const*. But what does “sufficiently apple-like” mean? If we are ever to constrain the find algorithm with Concepts, we need to be able to say in code what “apple-like” means for any apple and any orange.

    The Palo Alto TR doesn’t think that the mere existence of an operator== is enough. Instead, it defines the cross-type EqualityComparable concept as follows:

    template< typename T1, typename T2 >
    concept bool EqualityComparable =
        EqualityComparable<T1> &&
        EqualityComparable<T2> &&
        Common<T1, T2> &&
        EqualityComparable< std::common_type_t<T1, T2> > &&
        requires(T1 a, T2 b) {
            { a == b } -> bool;
            { b == a } -> bool;
            { a != b } -> bool;
            { b != a } -> bool;
            /* axioms:
                using C = std::common_type_t<T1, T2>;
                a == b <=> C{a} == C{b};
                a != b <=> C{a} != C{b};
                b == a <=> C{b} == C{a};
                b != a <=> C{b} != C{a};
            */
        };
    

    In words, what this says is for two different types to be EqualityComparable, they each individually must be EqualityComparable (i.e., with themselves), they must be comparable with each other, and (the key bit) they must share a common type which is also EqualityComparable, with identical semantics.

    The question then becomes: do std::string and char const * share a common type, to which they can both be converted, and which compares with the same semantics? In this case, the answer is trivial: std::string is the common type.

    Aside: why does the Palo Alto TR place this extra CommonType requirement on the argument to find when surely that will break some code that works and is “correct” today? It’s an interesting question. The justification is mathematical and somewhat philosophical: when you compare things for equality, you are asking if they have the same value. Just because someone provides an operator== to compare, say, an Employee with a SocialSecurityNumber doesn’t make an employee a social security number, or vice versa. If we want to be able to reason mathematically about our code (and we do), we have to be able to substitute like for like. Being able to apply equational reasoning to our programs is a boon, but we have to play by its rules.

    Readable and Common

    You may be wondering what any of this have to do with the Readable concept. Let’s look again at the concept as the Palo Alto TR defines it:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            { *i } -> const ValueType<I> &;
        };
    

    To my mind, what this is trying to say is there there is some substitutability, some mathematical equivalence, between an iterator’s reference type and its value type. EqualityComparable uses Common to enforce that substitutability. What if we tried to fix Readable in a similar way?

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            requires Common< ValueType<I>, decltype(*i) >;
        };
    

    Here we’re saying that for Readable types, the reference type and the value type must share a common type. The common type is computed using something like std::common_type_t, which basically uses the ternary conditional operator (?:). (I say “something like” since std::common_type_t isn’t actually up to the task. See lwg2408 and lwg2465.)

    Sadly, this doesn’t quite solve the problem. If you try to do common_type_t<unique_ptr<int>, unique_ptr<int>&> you’ll see why. It doesn’t work, despite the fact that the answer seems obvious. The trouble is that common_type always strips top-level const and reference qualifiers before testing for the common type with the conditional operator. For move-only types, that causes the conditional operator to barf.

    I’ve always found it a bit odd that common_type decays its arguments before testing them. Sometimes that’s what you want, but sometimes (like here) its not. Instead, what we need is a different type trait that test for the common type, but preserves reference and cv qualifications. I call it common_reference. It’s a bit of a misnomer though, since it doesn’t always return a reference type, although it might.

    The common reference of two types is the minimally qualified type to which objects of both types can bind. common_reference will try to return a reference type if it can, but fall back to a value type if it must. Here’s some examples to give you a flavor:

    Common reference… … result
    common_reference_t<int &, int const &> int const &
    common_reference_t<int &&, int &&> int &&
    common_reference_t<int &&, int &> int const &
    common_reference_t<int &, int> int

    With a common_reference type trait, we could define a CommonReference concept and specify Readable in terms of it, as follows:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            requires CommonReference<
                ValueType<I> &,
                decltype(*i) && >;
        };
    

    The above concept requires that there is some common reference type to which both *i and a mutable object of the iterator’s value type can bind.

    This, I think, is sufficiently general to type check all the iterators that are valid today, as well as iterators that return proxy references (though it takes some work to see that). We can further generalize this to accommodate the iter_move API I described in my previous post:

    template< typename I >
    concept bool Readable =
        Semiregular<I> &&
        requires(I i) {
            typename ValueType<I>;
            requires CommonReference<
                ValueType<I> &,
                decltype(*i) && >;          // (1)
            requires CommonReference<
                decltype(iter_move(i)) &&,
                decltype(*i) && >;          // (2)
            requires CommonReference<
                ValueType<I> const &,
                decltype(iter_move(i)) &&>; // (3)
        };
    

    OK, let’s see how this works in practice.

    Iterators and CommonReference

    First, let’s take the easy case of an iterator that returns a real reference like int&. The requirements are that its value type, reference type, and rvalue reference type satisfy the three CommonReference constraints above. (1) requires a common reference between int& and int&. (2), between int&& and int&, and (3) between int const& and int&&. These are all demonstrably true, so this iterator is Readable.

    But what about the zip iterator? Things here are much trickier.

    The three common reference constraints for the zip iterator amount to this:

    Common reference… … result
    common_reference_t<
    pair<int,int> &,
    pair<int&,int&> &&>
    ???
    common_reference_t<
    pair<int&&,int&&> &&,
    pair<int&,int&> &&>
    ???
    common_reference_t<
    pair<int,int> const &,
    pair<int&&,int&&> &&>
    ???

    Yikes. How is the common_reference trait supposed to evaluate this? The ternary conditional operator is just not up to the task.

    OK, let’s first imagine what we would like the answers to be. Taking the last one first, consider the following code:

    void foo( pair< X, Y > p );
    
    pair<int,int> const & a = /*...*/;
    pair<int &&,int &&> b {/*...*/};
    
    foo( a );
    foo( move(b) );
    

    If there are types that we can pick for X and Y that make this compile, then we can make pair<X,Y> the “common reference” for pair<int&&,int&&>&& and pair<int,int> const &. Indeed there are: X and Y should both be int const &.

    In fact, for each of the CommonReference constraints, we could make the answer pair<int const&,int const&> and be safe. So in principle, our zip iterator can model the Readable concept. W00t.

    But look again at this one:

    common_reference_t<pair<int,int> &, pair<int&,int&> &&>
    

    If this coughs up pair<int const&,int const&> then we’ve lost something in the translation: the ability to mutate the elements of the pair. In an ideal world, the answer would be pair<int&,int&> because a conversion from both pair<int,int>& and pair<int&,int&>&& would be safe and meets the “minimally qualified” spirit of the common_reference trait. But this code doesn’t compile:

    void foo( pair< int&,int& > p );
    
    pair<int,int> a;
    pair<int&,int&> b {/*...*/};
    
    foo( a );       // ERROR here
    foo( move(b) );
    

    Unfortunately, pair doesn’t provide this conversion, even though it would be safe in theory. Is that a defect? Perhaps. But it’s something we need to work with.

    Long story short, the solution I went with for range-v3 is to define my own pair-like type with the needed conversions. I call it common_pair and it inherits from std::pair so that things behave as you would expect. With common_pair and a few crafty specializations of common_reference, the Readable constraints are satisfied for the zip iterator as follows:

    Common reference… … result
    common_reference_t<
    pair<int,int> &,
    common_pair<int&,int&> &&>
    common_pair<int&,int&>
    common_reference_t<
    common_pair<int&&,int&&> &&,
    common_pair<int&,int&> &&>
    common_pair<int const&,int const&>
    common_reference_t<
    pair<int,int> const &,
    common_pair<int&&,int&&> &&>
    common_pair<int const&,int const&>

    Computing these types is not as tricky as it may appear at first. For types like pair<int,int>& and common_pair<int&,int&>&&, it goes like this:

    1. Distribute any top-level ref and cv qualifiers to the members of the pair. pair<int,int>& becomes pair<int&,int&>, and common_pair<int&,int&>&& becomes common_pair<int&,int&>.
    2. Compute the element-wise common reference, and bundle the result into a new common_pair, resulting in common_pair<int&,int&>.

    Generalizing

    Our zip iterator, with enough ugly hackery, can model our re-specified Readable concept. That’s good, but what about other proxy reference types, like vector<bool>‘s? If vector<bool>‘s reference type is bool_ref, then we would need to specialize common_reference such that the Readable constraints are satisfied. This will necessarily involve defining a type such that it can be initialized with either a bool_ref or with a bool&. That would be a decidedly weird type, but it’s not impossible. (Imagine a variant<bool&,bool_ref> if you’re having trouble visualizing it.)

    Getting vector<bool>‘s iterators to fit the mold is an ugly exercise in hackery, and actually using its common reference (the variant type) would incur a performance hit for every read and write. But the STL doesn’t actually need to use it. It just needs to exist.

    What is the point of jumping through these hoops to implement an inefficient type that in all likelihood will never actually be used? This is going to be unsatisfying for many, but the answer is for the sake of mathematical rigour. There must be some substitutability relationship between an iterator’s reference type and its value type that is enforceable. Requiring that they share a common reference is the best I’ve come up with so far. And as it turns out, this “useless” type actually does have some uses, as we’ll see in the next installment.

    Summary

    So here we are. There is a way to define the Readable concept — and hence the InputIterator concept — in a way that is general enough to permit proxy iterators while also saying something meaningful and useful about an iterator’s associated types. Actually defining a proxy iterator such that it models this concept is no small feat and requires extensive amounts of hack work. BUT IT’S POSSIBLE.

    One could even imagine defining a Universal Proxy Reference type that takes a getter and setter function and does all the hoop jumping to satisfy the Iterator concepts — one proxy reference to rule them all, if you will. That’s left as an exercise for the reader.

    If you made it this far, congratulations. You could be forgiven for feeling a little let down; this solution is far from ideal. Perhaps it’s just awful enough to spur a real discussion about how we could change the language to improve the situation.

    In the next installment, I’ll describe the final piece of the puzzle: how do we write the algorithm constraints such that they permit proxy iterators? Stay tuned.

    As always, you can find all code described here in my range-v3 repo on github.

    "\e"
  • Iterators++, Part 1

    In the last post, I described the so-called proxy iterator problem: the fact that iterators that return proxy references instead of real references don’t sit comfortably within the STL’s framework. Real, interesting, and useful iterators fall foul of this line, iterators like vector<bool>‘s or like the iterator of the zip view I presented. In this post, I investigate what we could do to bring proxy iterators into the fold — what it means for both the iterator concepts and for the algorithms. Since I’m a library guy, I restrict myself to talking about pure library changes.

    Recap

    As in the last post, we’ll use the zip view to motivate the discussion. Given two sequences like:

    vector<int> x{1,2,3,4};
    vector<int> y{9,8,7,6};
    

    …we can create a view by “zipping” the two into one, where each element of the view is a pair of corresponding elements from x and y:

    using namespace ranges;
    auto rng = view::zip(x, y);
    
    assert(*rng.begin() == make_pair(1,9));
    

    The type of the expression “*rng.begin()” — the range’s reference type — is pair<int&,int&>, and the range’s value type is pair<int,int>. The reference type is an example of a proxy: an object that stands in for another object, or in this case two other objects.

    Since both x and y are random access, the resulting zip view should be random access, too. But here we run foul of STL’s “real reference” requirement: for iterators other than input iterators, the expression *it must return a real reference. Why? Good question! The requirement was added sometime while the STL was being standardized. I can only guess it was because the committee didn’t know what it meant to, say, sort or reverse elements that aren’t themselves persistent in memory, and they didn’t know how to communicate to the algorithms that a certain temporary object (the proxy) is a stand-in for a persistent object. (Maybe someone who was around then can confirm or deny.)

    The real-reference requirement is quite restrictive. Not only does it mean the zip view can’t be a random access sequence, it also means that you can’t sort or reverse elements through a zip view. It’s also the reason why vector<bool> is not a real container.

    But simply dropping the real-reference requirement isn’t enough. We also need to say what it means to sort and reverse sequences that don’t yield real references. In the last post, I described three specific problems relating to constraining and implementing algorithms in the presence of proxy references.

    1. What, if anything, can we say about the relationship between an iterator’s value type and its reference type?
    2. How do we constrain higher-order algorithms like for_each and find_if that take functions that operate on a sequence’s elements?
    3. How do we implement algorithms that must swap and move elements around, like sort?

    Let’s take the last one first.

    Swapping and Moving Elements

    If somebody asked you in a job interview to implement std::reverse, you might write something like this:

    template< class BidiIter >
    void reverse( BidiIter begin, BidiIter end )
    {
        using std::swap;
        for(; begin != end && begin != --end; ++begin)
            swap(*begin, *end);
    }
    

    Congratulations, you’re hired. Now, if the interviewer asked you whether this algorithm works on the zip view I just described, what would you say? The answer, as you may have guessed, is no. There is no overload of swap that accepts pair rvalues. Even if there were, we’re on thin ice here with the zip view’s proxy reference type. The default swap implementation looks like this:

    template< class T >
    void swap( T & t, T & u )
    {
        T tmp = move(u);
        u = move(t);
        t = move(tmp);
    }
    

    Imagine what happens when T is pair<int&,int&>. The first line doesn’t move any values; tmp just aliases the values referred to by u. The next line stomps the values in u, which mutates tmp because it’s an alias. Then we copy those stomped values back to t. Rather than swapping values, this makes them both equal to t. Oops.

    If at this point you’re smugly saying to yourself that pair has its own swap overload that (almost) does the right thing, you’re very smart. Shut up. But if you’re saying that the above is not a standard-conforming reverse implementation because, unlike all the other algorithms, reverse is required to use iter_swap, then very good! That’s the clue to unraveling this whole mess.

    iter_swap

    iter_swap is a thin wrapper around swap that takes iterators instead of values and swaps the elements they refer to. It’s an exceedingly useless function, since iter_swap(a,b) is pretty much required to just call swap(*a,*b). But what if we allowed it to be a bit smarter? What if iter_swap were a full-fledged customization point that allowed proxied sequences to communicate to the algorithms how their elements should be swapped?

    Imagine the zip view’s iterators provided an iter_swap that knew how to truly swap the elements in the underlying sequences. It might look like this:

    template< class It1, class It2 >
    struct zip_iterator
    {
        It1 it1;
        It2 it2;
    
        /* ... iterator interface here... */
    
        friend void iter_swap(zip_iterator a, zip_iterator b)
        {
            using std::iter_swap;
            iter_swap(a.it1, b.it1);
            iter_swap(a.it2, b.it2);
        }
    };
    

    Now we would implement reverse like this:

    template< class BidiIter >
    void reverse( BidiIter begin, BidiIter end )
    {
        using std::iter_swap;
        for(; begin != end && begin != --end; ++begin)
            iter_swap(begin, end);
    }
    

    Voilร ! Now reverse works with zip views. That was easy. All that is required is (a) to advertise iter_swap as a customization point, and (b) use iter_swap consistently throughout the standard library, not just in reverse.

    iter_move

    We haven’t fixed the problem yet. Some algorithms don’t just swap elements; they move them. For instance stable_sort might allocate a temporary buffer and move elements into it while it works. You can’t use iter_swap to move an element into raw storage. But we can use a play from the iter_swap playbook to solve this problem. Let’s make an iter_move customization point that gives iterators a way to communicate how to move values out of the sequence.

    iter_move‘s default implementation is almost trivial:

    template< class I,
        class R = typename iterator_traits< I >::reference >
    conditional_t<
        is_reference< R >::value,
        remove_reference_t< R > &&,
        R >
    iter_move( I it )
    {
        return move(*it);
    }
    

    The only tricky bit is the declaration of the return type. If *it returns a temporary, we just want to return it by value. Otherwise, we want to return it by rvalue reference. If you pass a vector<string>::iterator to iter_move, you get back a string && as you might expect.

    How does the zip view implement iter_move? It’s not hard at all:

    template< class It1, class It2 >
    struct zip_iterator
    {
        It1 it1;
        It2 it2;
    
        /* ... iterator interface here... */
    
        friend auto iter_move(zip_iterator a)
        {
            using std::iter_move;
            using RRef1 = decltype(iter_move(a.it1));
            using RRef2 = decltype(iter_move(a.it2));
            return pair<RRef1, RRef2>{
                iter_move(a.it1),
                iter_move(a.it2)
            };
        }
    };
    

    The algorithms can use iter_move as follows:

    // Move an element out of the sequence and into a temporary
    using V = typename iterator_traits< I >::value_type;
    V tmp = iter_move( it );
    // Move the value back into the sequence
    *it = move( tmp );
    

    As an aside, this suggests a more general default implementation of iter_swap:

    template< class I >
    void iter_swap( I a, I b )
    {
        using V = typename iterator_traits< I >::value_type;
        V tmp = iter_move( a );
        *a = iter_move( b );
        *b = move( tmp );
    }
    

    Now proxy sequences like zip only have to define iter_move and they gets a semantically correct iter_swap for free. It’s analogous to how the default std::swap is defined in terms of std::move. (Doing it this way doesn’t pick up user-defined overloads of swap. That’s bad. There’s a work-around, but it’s beyond the scope of this post.)

    For a zip view that has value type pair<T,U> and reference type pair<T&,U&>, the return type of iter_move is pair<T&&,U&&>. Makes perfect sense. Take another look at the default implementation of iter_swap above and satisfy yourself that it correctly swaps zipped elements, even if the underlying sequences have move-only value types.

    One final note about iter_move: the implication is that to support proxied sequences, iterators need an extra associated type: the return type of iter_move. We can call it rvalue_reference and put it in iterator_traits alongside value_type and reference.

    Alternate Design

    I find the above design clean and intuitive. But it raises an interesting question: is it OK that iter_swap(a,b) and swap(*a,*b) might mean different things? Personally I think that’s OK, but let’s imagine for a moment that it’s not. What else could we do?

    An obvious alternate design is to overload swap for proxy references to swap the objects they refer to. Let’s imagine we add the following overload to namespace std:

    template< class T, class U >
    void swap( pair< T&, U& > && a, pair< T&, U& > && b )
    {
        swap(a.first, b.first);
        swap(a.second, b.second);
    }
    

    With enough SFINAE magic we could further generalize this to support swapping pairs of proxy references, but let’s stick with this. I could live with it.

    But as before, this isn’t enough; we would also need to overload move to take a pair<T&,U&> and return a pair<T&&,U&&>. And this is where I start getting uncomfortable, because move is used everywhere and it’s currently not a customization point. How much code is out there that assumes the type of a move expression is &&? What breaks when that’s no longer true?

    Purely as a matter of library evolution, overloading move that way for pairs of references is a non-starter because it would be changing the meaning of existing code. We could avoid the problem by changing zip‘s reference type from pair<T&,U&> to magic_proxy_pair< T&, U& > and overloading swap and move on that. magic_proxy_pair would inherit from pair, so most code would be none the wiser. Totally valid design.

    Summary, For Now

    I’ve run long at the mouth, and I still have two more issues to deal with, so I’ll save them for another post. We’ve covered a lot of ground. With the design suggested above, algorithms can permute elements in proxied sequences with the help of iter_swap and iter_move, and iterators get a brand new associated type called rvalue_reference.

    Whether you prefer this design or the other depends on which you find more distasteful:

    1. iter_swap(a,b) can be semantically different than swap(*a,*b), or
    2. move is a customization point that is allowed to return some proxy rvalue reference type.

    In the next installment, I’ll describe what we can say about the relationship between an iterator’s value type and its reference type (and now its rvalue reference type), and how we can constrain higher-order algorithms like for_each and find_if.

    As always, you can find all code described here in my range-v3 repo on github.

    "\e"
  • To Be or Not to Be (an Iterator)

    Way back in 1999, when the ink on the first C++ standard was still damp, Herb Sutter posed a GoTW puzzler in the still extant C++ Report (RIP): When Is a Container Not a Container? In that article, Herb described the problems of the now-infamous vector<bool>. According to the standard’s own container requirements, vector<bool> is not a container.

    In a nutshell, it’s because vector<bool>‘s iterators claim to be random-access, but they’re not. Random-access iterators, when you dereference them, must return a real reference. They can only do that if the thing they point to really exists somewhere. But the bool that a vector<bool>::iterator points to does not exist anywhere. It’s actually a bit in a packed integer, and dereferencing a vector<bool>‘s iterator returns an object of some type that merely acts like a bool& without actually being a bool&.

    Herb goes so far as to say this:

    […] although a proxied collection can be an important and useful tool, by definition it must violate the standard’s container requirements and therefore can never be a conforming container.

    At the end of his article, Herb suggests that people stop using vector<bool> and use std::bitset if they want bit-packing. But that just pushes the problem around. Why shouldn’t std::bitset be a conforming container with random-access iterators? If proxied collections are so useful, why should we content ourselves with a standard library that treats them like second-class citizens?

    A Brief History of Proxy Iterators

    Herb wrote his article in 1999, so we’ve been living with this problem for a long time. Many have tried to fix it and ultimately failed for one reason or another. Mostly it’s because all the solutions have tried to be backwards compatible, shoehorning a richer iterator hierarchy into a standard that doesn’t easily allow it, or else breaking iterators themselves apart into separate objects that control traversal and element access. Each time the committee has balked, preferring instead the devil it knew.

    An interesting historical note: the original STL design didn’t have the “true reference” requirement that causes the problem. Take a look at the SGI docs for the Forward Iterator concept. Nowhere does it say that *it should be a real reference. The docs for Trivial Iterators specifically mention proxy references and say they’re legit.

    Recently, a who’s who of C++ luminaries put their names on N3351, the so-called Palo Alto TR, which proposes a concept-based redesign of the STL, using the syntax of Concepts Lite. Interestingly, the Palo Alto TR is a throw-back to the original SGI design: there is no “true-reference” requirement on the return type of *it; it merely must be convertible to const ValueType<I> &:

    // This must work, according to the Palo Alto TR
    const ValueType<I> & val = *it;
    

    It’s not hard for a proxy reference type to provide such a conversion. For instance, the following compiles today:

    std::vector<bool> vb{true, false, true, false};
    auto it = vb.begin();
    const bool & val = *it;
    

    *it has an implicit conversion to bool, which binds to a const bool&. Awesome! So the problem is solved, right? Not quite.

    A Panoply of Proxy Problems

    To better see the problems with proxy iterators, let’s look at a more interesting example: a zip view. When you zip two sequences together, you get a single sequence where each element is a std::pair of elements from the two source sequences. This can be done lazily, creating pairs on demand as the zip view is iterated:

    std::vector<int> v1 { 1,2,3 };
    std::vector<int> v2 { 9,8,7 };
    
    auto z = view::zip( v1, v2 );
    auto it = z.begin();
    
    assert( *it   == std::make_pair(1,9) );
    assert( *++it == std::make_pair(2,8) );
    assert( *++it == std::make_pair(3,7) );
    

    Since the zip view is generating the pairs on demand, they don’t exist anywhere in memory. But the elements they refer to do! See?

    std::pair<int&,int&> p = *z.begin();
    assert( &p.first  == &v1[0] );
    assert( &p.second == &v2[0] );
    

    The zip view is a very interesting beastie. Its reference type is pair<T&,U&> and its value type is pair<T,U>. This poses some very interesting challenges for the iterator concepts.

    1. Values and References

    Recall that the Palo Alto TR requires *it to be convertible to const ValueType<I>&. So we should be able to do this:

    auto z = view::zip( v1, v2 );
    const pair<int,int>& val = *z.begin();
    

    That works! As it so happens, there is a conversion from std::pair<T&,U&> to std::pair<T,U> — but there’s a catch: it only works if T and U are copyable! And even when they’re not, it’s clear that copying is not the behavior one would expect when using *it to initialize a const reference. If T or U is expensive to copy, you’re not going to get the performance or the behavior you expect, and if it’s unique_ptr it’s not going to compile at all. ๐Ÿ™

    Requiring that an iterator’s reference type be convertible to const ValueType<I>& is over-constraining. But then what useful thing can we say about the relationship between these two types?

    2. Algorithm Constraints

    All the algorithm signatures in the Palo Alto TR use ValueType in the concept checks in order to constrain the templates. For example, here’s the constrained signature of for_each:

    template<InputIterator I, Semiregular F>
        requires Function<F, ValueType<I>>
    F for_each(I first, I last, F f);
    

    If you’re not familiar with C++ concepts, what lines 1 and 2 say is: first and last must satisfy the requirements of the InputIterator concept, F must be Semiregular (I’ll gloss over this bit), and it must be callable with one argument of the iterator’s value type.

    Now imagine code like this:

    // As before, v1 and v2 are vectors of ints:
    auto z = view::zip( v1, v2 );
    // Let Ref be the zip iterator's reference type:
    using Ref = decltype(*z.begin());
    // Use for_each to increment all the ints:
    for_each( z.begin(), z.end(), [](Ref r) {
        ++r.first;
        ++r.second;
    });
    

    This seems perfectly reasonable. The lambda accepts an object of the zip view’s reference type, which is a pair<int&,int&>, and then it increments both first and second members. But this doesn’t type-check. Why?

    Remember the concept check: Function<F, ValueType<I>>. The function we pass to for_each must be callable with an object of the iterator’s value type. In this case, the value type is pair<int,int>. There is no conversion from that to the type the function expects, which is pair<int&,int&>. Bummer.

    If we change the lambda to take a pair<int,int>&, then the concept check passes, but the template will fail to instantiate correctly. It’s easy to see why when you look at a typical for_each implementation:

    template<InputIterator I, Semiregular F>
    requires Function<F, ValueType<I>>
    F for_each(I first, I last, F f) {
        for(; first != last; ++first)
            f(*first);
        return f;
    }
    

    The lambda is called with *first which has type pair<int&,int&>, but that doesn’t convert to pair<int,int>&. Gah!!!

    The most galling bit is that the code we wrote above — the code with the lambda that takes the reference type — works just fine if we simply delete the requires Function<F, ValueType<I>> constraint. Clearly something is wrong with the constraints, the concepts, or our expectations.

    I should add that the problem is not specific to the zip view. Any sequence with a proxy reference type has this problem, vector<bool> included. If we just slap these constraints on the existing algorithms, some code that works today will break, and the only “fix” would be to stop using the standard algorithms. ๐Ÿ™

    3. Permutability of Move-Only Types

    Unfortunately, the problems don’t end there. The sort algorithm requires a sequence to be permutable; that is, you should be able to shuffle its elements around. And since it should support move-only types, that means that the sequence’s iterators should be indirectly-movable. The Palo Alto TR has this to say about it:

    The IndirectlyMovable and IndirectlyCopyable concepts describe copy and move relationships between the values of an input iterator, I, and an output iterator Out. For an output iterator out and an input iterator in, their syntactic requirements expand to:

    • IndirectlyMovable requires *out = move(*in)

    But what if *in returns a proxy? Then move(*in) is moving the proxy, not the object to which the proxy refers. In the case of sorting a zip view, we’re trying to move a (temporary) pair<T&,U&> into a pair<T&,U&>. As with issue (1), that won’t work at all for move-only types. But you would probably fail before that, at the sort requires clause, because of issue (2). Sheesh!

    Summary, For Now…

    Even though the Palo Alto TR lifts the over-constraining requirement that ForwardIterators return real references, the proxy iterator problem remains. On the one hand, it says that proxy iterators are OK. On the other hand, some interesting proxy iterators fail to model the Iterator concept or satisfy the algorithm constraints, and those that do don’t have the right semantics or performance characteristics. What are our options?

    1. The zip view, vector<bool>, and its ilk are useful, but are not legitimate containers and ranges, and the STL can’t support them, full stop; or
    2. The iterator concepts (and probably the algorithm constraints) as specified in the Palo Alto TR need to be tweaked somehow to support proxy iterators, and some algorithm implementations probably need to change, too; or
    3. The language needs to change to better support proxy references (an idea from Sean Parent); or
    4. Something else.

    I really don’t like option (1); there are too many interesting forward iterators that can’t return true references, and I’m tired of doing without. I have some rudimentary ideas about option (2) that I plan to describe in my next post. Option (3) can’t be ruled out, but IANALL (I Am Not A Language Lawyer) and have no idea what would be involved. It’s clear that with C++17 shaping up, and with the Concepts Lite TR finally reaching PDTS status , and a range-ified, concept-ified STL in the works, the time to start making decisions about this stuff is now.

    "\e"