[Effective-cpp] Item 1: Uses and Abuses of vector

Herb Sutter hsutter at microsoft.com
Tue Oct 26 18:02:08 EDT 2004


Re range checking: I think it's likely that the C++0x standard library
will include range checking on by default, in some form (e.g., saying
that vector's [] is range-checked, or providing alternative containers
that are range-checked by default). On modern architectures the cost is
often negligible to unmeasurable for real-world applications, and
continues to drop; predict the branch the right way and the cost can be
near-zero even in the increasingly rare truly CPU-bound code where it
could matter. At the same time, safety and security are increasingly
important. Having range checking off by default is therefore
increasingly difficult to defend. It has to be easy to write safe code,
and code that is safe by default.

Re lambda:

>> I agree, Lambda is a marvellous use of templates but I'd far rather
the
>> language supported it directly.
>
>How would you like this language support to look like? I.e. how would
you
>write my for_each() example, with language support for lambda
functions?

If you mean a general for_each, I'd like to replace code like

  for( iter = v.begin(); iter != v.end(); ++ iter {
    do stuff with iter
  }

with

  for_each( v.begin(), v.end(), lambda (i) {
    do stuff with i
  });

That is, each algorithm becomes a directly usable looping construct.

If you meant:

>vector<int> v;
>int x, y;
>...
>find_if(v.rbegin(), v.rend(), bind2nd(greater_equal<int>(), y));
>
>This may be written using BLL as:
>
>find_if(v.rbegin(), v.rend(), _1 >= y);

then I'd like to be able to write it as:

  find_if( v.begin(), v.end(), lambda (i) { return i >= y; } );

Now you get into closures (how to capture y, etc.). So that syntax
probably isn't exactly what we'd get, but that's the idea. Better still,
it could be nice to have the current lambda syntax supported as a
convenience shorthand for the simpler lambda functions:

  find_if( v.rbegin(), v.rend(), _1 >= y );

but with compiler/language support and good error messages, not deeply
weird messages about deep template machinery.

I think it could be a powerful idea to enable a situation where every
algorithm you write can become a new kind of loop construct that can be
used directly. Bjarne isn't yet convinced that this is a good thing, but
I'm convinced it could be important for all the reasons algorithms are
important (e.g., increasing the level at which we talk about our code,
when there's near-zero semantic information in the naked keywords "for"
and "while").

Herb





More information about the Effective-cpp mailing list