Paralysis of analysis -- the value/ref dilemma

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Wed Dec 15 07:56:36 PST 2010


On 12/15/10 8:34 AM, spir wrote:
> On Tue, 14 Dec 2010 13:53:39 -0600 Andrei
> Alexandrescu<SeeWebsiteForEmail at erdani.org>  wrote:
>
>> Coming from an STL background I was also very comfortable with the
>> notion of value. Walter pointed to me that in the STL what you
>> worry about most of the time is to _undo_ the propensity of objects
>> getting copied at the drop of a hat. For example, think of the
>> common n00b error of passing containers by value.
>>
>> So since we have the opportunity to decide now for eternity the
>> right thing, I think reference semantics works great with
>> containers.
>
> The issue for me in your reasoning is that what you are here talking
> about, and what your choice is based on, is _not_ reference
> _semantics_, but something like "indirection efficiency". This is
> optimization that clearly belongs to implementation and has nothing
> to do with semantics.

Optimization (or pessimization) is a concern, but not my primary one. My 
concern is: most of the time, do you want to work on a container or on a 
copy of the container? Consider this path-of-least-resistance code:

void fun(Container!int c) {
     ...
     c[5] += 42;
     ...
}

Question is, what's the most encountered activity? Should fun operate on 
whatever container it was passed, or on a copy of it? Based on extensive 
experience with the STL, I can say that in the overwhelming majority of 
cases you want the function to mess with the container, or look without 
touch (by means of const). It is so overwhelming, any code reviewer in 
an STL-based environment will raise a flag when seeing the C++ 
equivalent to the code above - ironically, even if fun actually does 
need a copy of its input! (The common idiom is to pass the container by 
constant reference and then create a copy of it inside fun, which is 
suboptimal.)

In contrast, most of the time you want to work on a copy of a string, so 
strings are commonly not containers. (This is nicely effected by string 
being defined as arrays of immutable characters.) However, you sometimes 
do need to mutate a string, which is why char[] is useful on occasion.


Andrei


More information about the Digitalmars-d mailing list