More tricky range semantics

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Jan 15 17:10:30 PST 2015


On Fri, Jan 16, 2015 at 01:58:15AM +0100, Joseph Rushton Wakeling via Digitalmars-d wrote:
> On 16/01/15 00:24, Andrei Alexandrescu via Digitalmars-d wrote:
> >That's right. To simplify the problem space we might decree that
> >forward (or better) ranges with reference semantics are not allowed.
> >-- Andrei
> 
> That would seem to place significant restrictions on the ability to
> define effective random number generators and related functionality
> ... ?

Not to mention, I just realized that while the example I used relied on
the interaction between reference and value types, a similar problem
exists with just value types alone. Using the same wrapper range I
posted, suppose now that R is not a reference type range, but an input
(non-forward) range, and that .save is not implemented. Then consider
this code:

	unittest {
		auto r = R(...);
		auto wrapped = WrapperRange(r);

		assert(wrapped.equal(expectedData));
		bool b = wrapped.empty;
	}

Quiz: what's the value of b?

.

.

.

Go on, guess. :-)

.

.

.

Yup, b == false. Now guess what happens if you then access
wrapped.front?

Well, that depends. If someCondition became true before r was exhausted,
then wrapped.front would return a value that shouldn't be in the wrapped
range, because it breaks the invariant that WrapperRange is supposed to
stop when someCondition becomes true. However, if someCondition didn't
become true and r was exhausted, accessing wrapped.front will call
.front on an empty input range, which is UB. If you're lucky, you'll hit
an assert; otherwise, anything could happen, like dereferencing a
dangling pointer, reading invalid memory, etc..

So actually, my previous statement was not broad enough: this problem
happens not just with reference type ranges; it happens with
non-reference input ranges too!


T

-- 
If it breaks, you get to keep both pieces. -- Software disclaimer notice


More information about the Digitalmars-d mailing list