0

Using Range library for C++14/17/20 extension I noticed that when i store some results of range::views::method() operations that, during runtime, every change or update of the original data will cause the same changes to it's new constructed results, even after the event (instruction).

A link is there, but what is the pattern, what should we know about it ?

In this example, i used ranges::views::reverse()

#include <iostream>
#include <vector>
#include <range/v3/all.hpp>

int main()
{

   std::vector<int> values{1,2,3,4,5};

   auto reversed = ranges::views::reverse(values);

   values[3] = 0;

   for(auto const& it : values){
    std::cout<<it<<" ";
   }

   std::cout<<std::endl;

   for(auto const& it : reversed){
    std::cout<<it<<" ";
   }

    return 0;
}

Output:

  1 2 3 0 5
  5 0 3 2 1

The 4th value is changed for values, so for reversed too.

cigien
  • 57,834
  • 11
  • 73
  • 112
rekkalmd
  • 171
  • 1
  • 12

1 Answers1

2

Yes, because that is the intended behavior of ranges::views. It's supposed to be a non-owning view on some data. If that underlying data changes, then the view has no choice but to see those changes, since it doesn't have its own data that holds on to the previous state.

One exception to this is ranges::views::single which holds on to its own copy of the underlying data. Here's a demo.

cigien
  • 57,834
  • 11
  • 73
  • 112