Difference between range `save` and copy constructor

Paul Backus snarwin at gmail.com
Sun Feb 16 17:53:36 UTC 2020


On Sunday, 16 February 2020 at 17:10:24 UTC, Jonathan M Davis 
wrote:
> On Sunday, February 16, 2020 7:29:11 AM MST uranuz via
>> This is working fine with disabled postblit...
>> import std;
>>
>> struct SS
>> {
>>      @disable this(this); // Disabled copy
>>
>>      bool _empty = false;
>>
>>      bool empty() @property {
>>          return _empty;
>>      }
>>
>>      void popFront() {
>>         _empty = true;
>>      }
>>
>>      int front() @property { return 10; }
>> }
>>
>>
>> void main()
>> {
>>      foreach( it; SS() ) { writeln(it); }
>> }
>>
>> Am I missing something?
>
> That code compiles, because you're passing a temporary to 
> foreach. So, the compiler does a move instead of a copy. It's 
> the difference between
>
> auto ss = SS();
>
> and
>
> SS ss;
> auto ss2 = ss;
>
> If your main were
>
>     void main()
>     {
>         SS ss;
>         foreach( it; ss ) { writeln(it); }
>     }
>
> then it would not compile.

On the other hand, this does work:

     void main()
     {
         SS ss;
         foreach( it; move(ss) ) { writeln(it); }
     }

So perhaps the correct approach is to use `move` when copying 
input ranges.


More information about the Digitalmars-d-learn mailing list