-preview=in might break code

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sat Oct 3 16:27:27 UTC 2020


On 10/3/20 11:58 AM, Steven Schveighoffer wrote:
> What I don't agree with is the idea that one can write code expecting 
> something is passed by value, and then have the compiler later switch it 
> to a reference. `in` means by value in all code today. The fact that we 
> tried -preview=in on a bunch of projects and they "didn't break" is not 
> reassuring.

Agreed. Sadly I found (actually remembered) a smoking gun.

Over the years I've worked on a few STL-related code (such as 
flex_string and fbvector). I've once had a really difficult bug related 
to one or both of these functions:

http://www.cplusplus.com/reference/string/string/replace/
https://en.cppreference.com/w/cpp/algorithm/replace

The code looked correct and everything, I looked at it for hours. STL 
implementation subtleties are not really something to google about, but 
I asked a colleague and he started chuckling. He pointed out that you 
always must assume that your parameters may alias part of your 
container. (Sometimes wrapped in a different kind of iterator.) This 
sort of thing is well known and feared in STL implementer circles, so 
the rest of us sleep soundly at night.

Consider for example:

template< class ForwardIt, class T >
constexpr void replace( ForwardIt first, ForwardIt last,
                         const T& old_value, const T& new_value );

That may as well be called like this:

vector<Widget> v;
...
size_t i = ..., j = ...;
replace(v.begin(), v.end(), v[i], v[j]);

Only one is needed to be a reference inside the vector. Two is a worst 
case of sorts. You don't know what town you're in after debugging this.

At least in the STL this is reproducible with some ease, because STL 
always passes references. Now consider that this happens only on certain 
definitions of Widget (possibly maintenance increases its size and... 
boom!) and on certain platforms.

So I ask again: is this the kind of feature we want for the D language?


More information about the Digitalmars-d mailing list