[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: ? about C++



begin  Dimitri Maziuk  quotation:

> Anyhow, my point was, name 4 problem areas in C.
> 
> 1. No array bounds checking (Fix: use vector<> or equivalent)

Of course, the behavior of vector::operator[] is undefined if the index
is invalid, which is sort of weird, since vector::at() does the right
thing.

> 2. Pointers (Fix: use references, iterators etc.).

Iterators help a lot with STL collections, but references aren't all
that great. They're mostly just syntactic sugar, useful for, e.g.,
operator overloading, where you typically define, say, operator+= as:

   class X { X& operator+=(const X& x); };

This is really why references exist in C++ at all, because without them,
you'd either have to pass the argument to operator+= (and similar
operators) by value, which is inefficient for non-trivial objects (and
not always possible), or as a pointer, which would be syntactically ugly
(e.g.: "Object x, y; x += &y;").

There is, unfortunately, such a thing as a null reference (consider the
expression "X& x = *((X*) 0);", for a trivial and obvious example). On
the plus side, you can't index off a reference without explicitly
converting it to a pointer first.

The other annoying thing about references in C++ is that every time you
define some function that takes another object by reference, you get to
argue with yourself about whether it should be a pointer or a reference,
which in turn depends on where the object is coming from. More often
than not, it might as well be a pointer, because if the object was
created by "new" then you've already got a pointer to it anyway. And
creating references from pointers (e.g. "X* p; X& x = *p;") is ugly and
leads people to forget that the object may not exist (null pointer).

Craig

Attachment: pgprFkrq2xfur.pgp
Description: PGP signature


Reply to: