Improved Iterators with Ranges

Improved Iterators with Ranges

This post is a cross-post from www.ModernesCpp.org.

There are more reasons to prefer ranges library above the classical Standard Template Library. The ranges iterators support unified lookup rules and provide additional safety guarantees.

Unified Lookup Rules

Assume you want to implement a generic function that calls begin on a given container. The question is if the function calling begin on a container should assume a free begin function or a member function begin?

// begin.cpp

#include <cstddef>
#include <iostream>
#include <ranges>

struct ContainerFree {                                        // (1)
    ContainerFree(std::size_t len): len_(len), data_(new int[len]){}
    size_t len_;
    int* data_;
};
int* begin(const ContainerFree& conFree) {                   // (2)
    return conFree.data_;
}

struct ContainerMember {                                     // (3)
    ContainerMember(std::size_t len): len_(len), data_(new int[len]){}
    int* begin() const {                                     // (4)
        return data_;
    }
    size_t len_;
    int* data_;
};

void callBeginFree(const auto& cont) {                        // (5)
    begin(cont);
}

void callBeginMember(const auto& cont) {                      // (6)
    cont.begin();
}
 
int main() {

    const ContainerFree contFree(2020);
    const ContainerMember contMemb(2023);

    callBeginFree(contFree);                                 
    callBeginMember(contMemb);

    callBeginFree(contMemb);                                  // (7)
    callBeginMember(contFree);                                // (8)
   
}        

ContainerFree (line 1) has a free function begin (line 2), and ContainerMember (line 3) has a member function begin (line 4). Accordingly, contFree can use the generic function callBeginFree using the free function call begin(cont) (line 5), and contMemb can use the generic function callBeginMember using the member function call cont.begin (line 6). When I invoke callBeginFree and callBeginMember with the inappropriate containers in lines (7) and (8), the compilation fails.

No alt text provided for this image

I can solve this issue by providing two different begin implementations in two ways: classical and range based.

// beginSolved.cpp

#include <cstddef>
#include <iostream>
#include <ranges>

struct ContainerFree {
    ContainerFree(std::size_t len): len_(len), data_(new int[len]){}
    size_t len_;
    int* data_;
};
int* begin(const ContainerFree& conFree) {
    return conFree.data_;
}

struct ContainerMember {
    ContainerMember(std::size_t len): len_(len), data_(new int[len]){}
    int* begin() const {
        return data_;
    }
    size_t len_;
    int* data_;
};

void callBeginClassical(const auto& cont) {
    using std::begin;                          // (1)
    begin(cont);
}

void callBeginRanges(const auto& cont) {
    std::ranges::begin(cont);                  // (2)
}
 
int main() {

    const ContainerFree contFree(2020);
    const ContainerMember contMemb(2023);

    callBeginClassical(contFree);
    callBeginRanges(contMemb);

    callBeginClassical(contMemb);
    callBeginRanges(contFree);
   
}        

The classical way to solve this issue is to bring std::begin into the scope with a so-called using declaration (line 1). Thanks to ranges, you can directly use std::ranges::begin (line 2). std::ranges::begin considers both implementations of begin: the free version and the member function.

Finally, let me write about safety.

Safety

Let me start with iterators.

Iterators

The ranges library provides the expected operations to access the range.

No alt text provided for this image

When you use these operations for accessing the underlying range, there is a big difference. The compilation fails when you use the range access on the std::ranges's variant if the argument is an rvalue. On the contrary, using the same operation from the classical std namespace is undefined behavior.

// rangesAccess.cpp

#include <iterator>
#include <ranges>
#include <vector>

int main() {

    auto beginIt1 = std::begin(std::vector<int>{1, 2, 3});
    auto beginIt2 = std::ranges::begin(std::vector<int>{1, 2, 3});

}        

std::ranges::begin provides only overloads for lvalues. The temporary vector std::vector{1, 2, 3} is an rvalue. Consequentially, the compilation of the program fails.

No alt text provided for this image

The abbreviations lvalue and rvalue stand for locatable value and readable value.

  • lvalue (locatable value): A locatable value is an object that has a location in memory, and you can, therefore, determine its address. An lvalue has an identity.
  • rvalue (readable value): A rvalue is a value you can only read from. It does not represent an object in memory, and you cannot determine its address.

I have to admit to you that my short explanations of lvalues and rvalues is a simplification. If you want to know more details about value categories, read the following post Value Categories.

By the way, not only iterators but also views provide these additional safety guarantees.

Views

Views do not own data. Therefore, views do not extend the lifetime of their data. Consequently, views can only be created on lvalues. The compilation fails if you create a view on a temporary range.

// temporaryRange.cpp

#include <initializer_list>
#include <ranges>


int main() {

    const auto numbers = {1, 2, 3, 4, 5};

    auto firstThree = numbers | std::views::drop(3);             // (1)
    // auto firstThree = {1, 2, 3, 4, 5} | std::views::drop(3);  // (2)

    std::ranges::drop_view firstFour{numbers, 4};                // (3)
   // std::ranges::drop_view firstFour{{1, 2, 3, 4, 5}, 4};      // (4)
   
}        

When lines 1 and 3 are used with the lvalue numbers, all is fine. On the contrary, using the commented-out lines 2 and 4 on the rvalue std::initializer_list<int> {1, 2, 3, 4, 5}, causes the GCC compiler to complain verbosely:

No alt text provided for this image

What's next?

In my next post, I do my first peek into the C++23 future. In particular, the ranges library will get many improvements. There is with std::ranges::to a convenient way to construct containers from ranges. Additionally, we will get almost twenty new algorithms. Here are a few of them: std::views::chunk_by, std::views::slide, std::views::join_with, std::views::zip_transform, and std::views::adjacent_transform.


Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dr?ge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschl?ger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Ralf Holly, Juan Dent, George Liao, and Daniel Ceperley.

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, and Mipko.

My special thanks to Embarcadero

My special thanks to PVS-Studio

?

Mentoring Program

My new mentoring program "Fundamentals for C++ Professionals" starts on the 22nd of April. Get more information here: https://bit.ly/MentoringProgramModernesCpp.

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++

要查看或添加评论,请登录

Rainer Grimm的更多文章

社区洞察

其他会员也浏览了