Java or C++?

NickC ncoghlan at gmail.com
Mon Apr 21 09:14:08 EDT 2008


On Apr 15, 1:46 pm, Brian Vanderburg II <BrianVanderbu... at aim.com>
wrote:
> This will automatically call the constructors of any contained objects
> to initialize the string.  The implicit assignment operator
> automatically performs the assignment of any contained objects.
> Destruction is also automatic.  When 'p1' goes out of scope, during the
> destructor the destructor for all contained objects is called.

Yeah, C++ does try to be helpful, and all of those automatic copy
constructor, assignment operator and destructor implementations screw
up royally when confronted with pointers (and being able to use
pointers is basically the whole reason for bothering to write anything
in C or C++ in the first place). Code which relies on these default
method implementations is almost certain to be rife with memory leaks
and double-free bugs. So instead of being a convenience, they become a
painfully easy way of writing code that silently does some very, very
wrong things.

Other things like methods (including destructors!) being non-virtual
by default also make C++ code annoyingly easy to get wrong (without it
obviously looking wrong).

The whole design of C++ is riddled with premature optimisation of
speed and memory usage in the default settings, instead of choosing
safe defaults and providing concise ways of allowing the programmer to
say "I know optimisation X is safe here, please use it".

And the result? Any serious project in the language has to adopt it's
own techniques for avoiding all those traps, and those techniques are
likely to eliminate any supposed optimisations provided by the choices
of the C++ committee, while filling a code base with boilerplate that
only exists for the purpose of working around defects in the language
design (Scott Meyers has written at length about the worst of these
issues, far more clearly and eloquently than I ever could [1]).

That said, C++ code has one *huge* benefit over ordinary C code, which
is scope-controlled deletion of objects, and the associated Resource-
Acquisition-Is-Initialisation model. Even without using exceptions
(although those are handy as well), RAII is an excellent way of
guaranteeing that memory is freed, files are closed, or other
resources are released when a block of code is finished. RAII was
actually one of the inspirations behind the final form of PEP 343's
with statement.

Cheers,
Nick.

[1]http://www.amazon.com/Effective-Specific-Addison-Wesley-
Professional-Computing/dp/0201924889



More information about the Python-list mailing list