C/C++ style Crashes?

Steve Horne stephenwantshornenospam100 at aol.com
Sun Jan 14 18:27:40 PST 2007


On Fri, 12 Jan 2007 04:02:50 +0100, Sebastian Biallas
<groups.5.sepp at spamgourmet.com> wrote:

>Steve Horne wrote:
>> In a systems language, pointer arithmetic is a necessity. There are
>> things you simply cannot do without it - data structures that require
>> it, for instance.
>
>Can you give an example?

A particular favorite of mine allows doubly-linked list behaviour
using a single link per item - very useful if you need extremely large
lists of small items (though a custom allocator is essential). Each
link is actually the bitwise exclusive-or of the addresses of the
previous and next items. This may sound impossible to iterate, but if
the iterator contains two pointers pointing to two adjacent items, it
is actually quite easy to step in either direction. Stepping always
requires a bitwise exclusive-or of a pointer, and inserts and deletes
require multiple bitwise exclusive-ors on pointers.

In addition, pointer casting is useful for managing template bloat.
The basic approach is to write type-unsafe non-template code, and then
use a template to add a typesafe wrapper. But in many cases, more
flexibility is needed than can be handled using simple pointer
casting.

For example, consider a library to handle flexible tree data
structures. The container being implemented may or may not have a key
field. It may or may not have a data field. It may or may not have
subtree summary data stored within nodes. The non-template part needs
a way to access fields such that the position within a node struct (of
an unknown datatype) is determined at run-time.

The most efficient way to handle this depends on what kind of
operation is being implemented. A single data structure may have two
or more ways to access the same field, just to ensure that all
operations can be handled efficiently - many accesses will probably be
done as part of small functions supplied by the typesafe wrapper, to
keep the call overheads down in inner loops. But for many accesses,
the best approach is using the offset of a field relative to the start
of a node - a relative address. The non-template code gets the
relative addresses it needs from a data block provided by the typesafe
wrapper, which does a similar job to that done by virtual tables in
method calls.

-- 
Remove 'wants' and 'nospam' from e-mail.



More information about the Digitalmars-d mailing list