home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / libgpp.i02 < prev    next >
Encoding:
GNU Info File  |  1993-06-12  |  47.5 KB  |  1,082 lines

  1. This is Info file libgpp, produced by Makeinfo-1.47 from the input file
  2. libgpp.tex.
  3.  
  4. START-INFO-DIR-ENTRY
  5. * Libg++: (libg++).        The g++ library.
  6. END-INFO-DIR-ENTRY
  7.  
  8.    This file documents the features and implementation of The GNU C++
  9. library
  10.  
  11.    Copyright (C) 1988, 1991, 1992 Free Software Foundation, Inc.
  12.  
  13.    Permission is granted to make and distribute verbatim copies of this
  14. manual provided the copyright notice and this permission notice are
  15. preserved on all copies.
  16.  
  17.    Permission is granted to copy and distribute modified versions of
  18. this manual under the conditions for verbatim copying, provided also
  19. that the section entitled "GNU Library General Public License" is
  20. included exactly as in the original, and provided that the entire
  21. resulting derived work is distributed under the terms of a permission
  22. notice identical to this one.
  23.  
  24.    Permission is granted to copy and distribute translations of this
  25. manual into another language, under the above conditions for modified
  26. versions, except that the section entitled "GNU Library General Public
  27. License" and this permission notice may be included in translations
  28. approved by the Free Software Foundation instead of in the original
  29. English.
  30.  
  31. 
  32. File: libgpp,  Node: Proto,  Next: Representations,  Prev: OK,  Up: Top
  33.  
  34. Introduction to container class prototypes
  35. ******************************************
  36.  
  37.    As a temporary mechanism enabling the support of generic classes,
  38. the GNU C++ Library distribution contains a directory (`g++-include')
  39. of files designed to serve as the basis for generating container
  40. classes of specified elements.  These files can be used to generate
  41. `.h' and `.cc' files in the current directory via a supplied shell
  42. script program that performs simple textual substitution to create
  43. specific classes.
  44.  
  45.    While these classes are generated independently, and thus share no
  46. code, it is possible to create versions that do share code among
  47. subclasses. For example, using `typedef void* ent', and then generating
  48. a `entList' class, other derived classes could be created using the
  49. `void*' coercion method described in Stroustrup, pp204-210.
  50.  
  51.    This very simple class-generation facility is useful enough to serve
  52. current purposes, but will be replaced with a more coherent mechanism
  53. for handling C++ generics in a way that minimally disrupts current
  54. usage. Without knowing exactly when or how parametric classes might be
  55. added to the C++ language, provision of this simplest possible
  56. mechanism, textual substitution, appears to be the safest strategy,
  57. although it does require certain redundancies and awkward constructions.
  58.  
  59.    Specific classes may be generated via the `genclass' shell script
  60. program. This program has arguments specifying the kinds of base
  61. types(s) to be used. Specifying base types requires two arguments. The
  62. first is the name of the base type, which may be any named type, like
  63. `int' or `String'. Only named types are supported; things like `int*'
  64. are not accepted. However, pointers like this may be used by supplying
  65. the appropriate typedefs (e.g., editing the resulting files to include
  66. `typedef int* intp;'). The type name must be followed by one of the
  67. words `val' or `ref', to indicate whether the base elements should be
  68. passed to functions by-value or by-reference.
  69.  
  70.    You can specify basic container classes using `genclass base
  71. [val,ref] proto', where `proto' is the name of the class being
  72. generated.  Container classes like dictionaries and maps that require
  73. two types may be specified via `genclass -2 keytype [val, ref],
  74. basetype [val, ref] proto', where the key type is specified first and
  75. the contents type second.  The resulting classnames and filenames are
  76. generated by prepending the specified type names to the prototype names,
  77. and separating the filename parts with dots.  For example, `genclass
  78. int val List' generates class `intList' residing in files `int.List.h'
  79. and `int.List.cc'. `genclass -2 String ref int val VHMap' generates
  80. (the awkward, but unavoidable) class name `StringintVHMap'. Of course,
  81. programmers may use `typedef' or simple editing to create more
  82. appropriate names.  The existence of dot seperators in file names
  83. allows the use of GNU make to help automate configuration and
  84. recompilation. An example Makefile exploiting such capabilities may be
  85. found in the `libg++/proto-kit' directory.
  86.  
  87.    The `genclass' utility operates via simple text substitution using
  88. `sed'. All occurrences of the pseudo-types `<T>' and `<C>' (if there
  89. are two types) are replaced with the indicated type, and occurrences of
  90. `<T&>' and `<C&>' are replaced by just the types, if `val' is
  91. specified, or types followed by "&" if `ref' is specified.
  92.  
  93.    Programmers will frequently need to edit the `.h' file in order to
  94. insert additional `#include' directives or other modifications.  A
  95. simple utility, `prepend-header' to prepend other `.h' files to
  96. generated files is provided in the distribution.
  97.  
  98.    One dubious virtue of the prototyping mechanism is that, because
  99. sources files, not archived library classes, are generated, it is
  100. relatively simple for programmers to modify container classes in the
  101. common case where slight variations of standard container classes are
  102. required.
  103.  
  104.    It is often a good idea for programmers to archive (via `ar')
  105. generated classes into `.a' files so that only those class functions
  106. actually used in a given application will be loaded. The test
  107. subdirectory of the distribution shows an example of this.
  108.  
  109.    Because of `#pragma interface' directives, the `.cc' files should be
  110. compiled with `-O' or `-DUSE_LIBGXX_INLINES' enabled.
  111.  
  112.    Many container classes require specifications over and above the base
  113. class type. For example, classes that maintain some kind of ordering of
  114. elements require specification of a comparison function upon which to
  115. base the ordering.  This is accomplished via a prototype file `defs.hP'
  116. that contains macros for these functions. While these macros default to
  117. perform reasonable actions, they can and should be changed in
  118. particular cases. Most prototypes require only one or a few of these.
  119. No harm is done if unused macros are defined to perform nonsensical
  120. actions. The macros are:
  121.  
  122. `DEFAULT_INITIAL_CAPACITY'
  123.      The intitial capacity for containers (e.g., hash tables) that
  124.      require an initial capacity argument for constructors. Default: 100
  125.  
  126. `<T>EQ(a, b)'
  127.      return true if a is considered equal to b for the purposes of
  128.      locating, etc., an element in a container. Default: (a == b)
  129.  
  130. `<T>LE(a, b)'
  131.      return true if a is less than or equal to b Default: (a <= b)
  132.  
  133. `<T>CMP(a, b)'
  134.      return an integer < 0 if a<b, 0 if a==b, or > 0 if a>b. Default:
  135.      (a <= b)? (a==b)? 0 : -1 : 1
  136.  
  137. `<T>HASH(a)'
  138.      return an unsigned integer representing the hash of a. Default:
  139.      hash(a) ; where extern unsigned int hash(<T&>). (note: several
  140.      useful hash functions are declared in builtin.h and defined in
  141.      hash.cc)
  142.  
  143.    Nearly all prototypes container classes support container traversal
  144. via `Pix' pseudo indices, as described elsewhere.
  145.  
  146.    All object containers must perform either a `X::X(X&)' (or `X::X()'
  147. followed by `X::operator =(X&)') to copy objects into containers.  (The
  148. latter form is used for containers built from C++ arrays, like
  149. `VHSets'). When containers are destroyed, they invoke `X::~X()'.  Any
  150. objects used in containers must have well behaved constructors and
  151. destructors. If you want to create containers that merely reference
  152. (point to) objects that reside elsewhere, and are not copied or
  153. destroyed inside the container, you must use containers of pointers,
  154. not containers of objects.
  155.  
  156.    All prototypes are designed to generate *HOMOGENOUS* container
  157. classes.  There is no universally applicable method in C++ to support
  158. heterogenous object collections with elements of various subclasses of
  159. some specified base class. The only way to get heterogenous structures
  160. is to use collections of pointers-to-objects, not collections of objects
  161. (which also requires you to take responsibility for managing storage for
  162. the objects pointed to yourself).
  163.  
  164.    For example, the following usage illustrates a commonly encountered
  165. danger in trying to use container classes for heterogenous structures:
  166.  
  167.      class Base { int x; ...}
  168.      class Derived : public Base { int y; ... }
  169.      
  170.      BaseVHSet s; // class BaseVHSet generated via something like
  171.                   // `genclass Base ref VHSet'
  172.      
  173.      void f()
  174.      {
  175.        Base b;
  176.        s.add(b); // OK
  177.      
  178.        Derived d;
  179.        s.add(d);  // (CHOP!)
  180.      }
  181.  
  182.    At the line flagged with `(CHOP!)', a `Base::Base(Base&)' is called
  183. inside `Set::add(Base&)'--*not* `Derived::Derived(Derived&)'. 
  184. Actually, in `VHSet', a `Base::operator =(Base&)', is used instead to
  185. place the element in an array slot, but with the same effect.  So only
  186. the Base part is copied as a `VHSet' element (a so-called
  187. chopped-copy). In this case, it has an `x' part, but no `y' part; and a
  188. Base, not Derived, vtable. Objects formed via chopped copies are rarely
  189. sensible.
  190.  
  191.    To avoid this, you must resort to pointers:
  192.  
  193.      typedef Base* BasePtr;
  194.      
  195.      BasePtrVHSet s; // class BaseVHSet generated via something like
  196.                      // `genclass BasePtr val VHSet'
  197.      
  198.      void f()
  199.      {
  200.        Base* bp = new Base;
  201.        s.add(b);
  202.      
  203.        Base* dp = new Derived;
  204.        s.add(d);  // works fine.
  205.      
  206.        // Don't forget to delete bp and dp sometime.
  207.        // The VHSet won't do this for you.
  208.      }
  209.  
  210. Example
  211. =======
  212.  
  213.    The prototypes can be difficult to use on first attempt. Here is an
  214. example that may be helpful. The utilities in the `proto-kit' simplify
  215. much of the actions described, but are not used here.
  216.  
  217.    Suppose you create a class `Person', and want to make an Map that
  218. links the social security numbers associated with each person. You start
  219. off with a file `Person.h'
  220.  
  221.  
  222.      #include <String.h>
  223.      
  224.      class Person
  225.      {
  226.        String nm;
  227.        String addr;
  228.        //...
  229.      public:
  230.        const String& name() { return nm; }
  231.        const String& address() { return addr; }
  232.        void          print() { ... }
  233.        //...
  234.      }
  235.  
  236.    And in file `SSN.h',
  237.  
  238.      typedef unsigned int SSN;
  239.  
  240.    Your first decision is what storage/usage strategy to use. There are
  241. several reasonable alternatives here: You might create an "object
  242. collection" of Persons, a "pointer collection" of pointers-to-Persons,
  243. or even a simple String map, housing either copies of pointers to the
  244. names of Persons, since other fields are unused for purposes of the
  245. Map. In an object collection, instances of class Person "live" inside
  246. the Map, while in a pointer collection, the instances live elswhere.
  247. Also, as above, if instances of subclasses of Person are to be used
  248. inside the Map, you must use pointers. In a String Map, the same
  249. difference holds, but now only for the name fields. Any of these
  250. choices might make sense in particular applications.
  251.  
  252.    The second choice is the Map implementation strategy. Either a tree
  253. or a hash table might make sense. Suppose you want an AVL tree Map.
  254. There are two things to now check. First, as an object collection, the
  255. AVLMap requires that the elsement class contain an `X(X&)' constructor.
  256. In C++, if you don't specify such a constructor, one is constructed for
  257. you, but it is a very good idea to always do this yourself, to avoid
  258. surprises. In this example, you'd use something like
  259.      class Person
  260.      { ...;
  261.          Person(const Person& p) :nm(p.nm), addr(p.addr) {}
  262.      };
  263.  
  264.    Also, an AVLMap requires a comparison function for elements in order
  265. to maintain order. Rather than requiring you to write a particular
  266. comparison function, a `defs' file is consulted to determine how to
  267. compare items. You must create and edit such a file.
  268.  
  269.    Before creating `Person.defs.h', you must first make one additional
  270. decision. Should the Map member functions like `m.contains(p)' take
  271. arguments (`p') by reference (i.e., typed as `int Map::contains(const
  272. Person& p)' or by value (i.e., typed as `int Map::contains(const Person
  273. p)'. Generally, for user-defined classes, you want to pass by
  274. reference, and for builtins and pointers, to pass by value. SO you
  275. should pick by-reference.
  276.  
  277.    You can now create `Person.defs.h' via `genclass Person ref defs'.
  278. This creates a simple skeleton that you must edit. First, add `#include
  279. "Person.h"' to the top. Second, edit the `<T>CMP(a,b)' macro to compare
  280. on name, via
  281.  
  282.      #define <T>CMP(a, b) ( compare(a.name(), b.name()) )
  283.  
  284. which invokes the `int compare(const String&, const String&)' function
  285. from `String.h'. Of course, you could define this in any other way as
  286. well. In fact, the default versions in the skelaton turn out to be OK
  287. (albeit inefficient) in this particular example.
  288.  
  289.    You may also want to create file `SSN.defs.h'. Here, choosing
  290. call-by-value makes sense, and since no other capabilities (like
  291. comparison functions) of the SSNs are used (and the defaults are OK
  292. anyway), you'd type
  293.  
  294.      genclass SSN val defs
  295.  
  296. and then edit to place `#include "SSN.h"' at the top.
  297.  
  298.    Finally, you can generate the classes. First, generate the base
  299. class for Maps via
  300.  
  301.      genclass -2 Person ref SSN val Map
  302.  
  303. This generates only the abstract class, not the implementation, in file
  304. `Person.SSN.Map.h' and `Person.SSN.Map.cc'.  To create the AVL
  305. implementation, type
  306.  
  307.      genclass -2 Person ref SSN val AVLMap
  308.  
  309. This creates the class `PersonSSNAVLMap', in `Person.SSN.AVLMap.h' and
  310. `Person.SSN.AVLMap.cc'.
  311.  
  312.    To use the AVL implementation, compile the two generated `.cc'
  313. files, and specify `#include "Person.SSN.AVLMap.h"' in the application
  314. program. All other files are included in the right ways automatically.
  315.  
  316.    One last consideration, peculiar to Maps, is to pick a reasonable
  317. default contents when declaring an AVLMap. Zero might be appropriate
  318. here, so you might declare a Map,
  319.  
  320.      PersonSSNAVLMap m((SSN)0);
  321.  
  322.    Suppose you wanted a `VHMap' instead of an `AVLMap' Besides
  323. generating different implementations, there are two differences in how
  324. you should prepare the `defs' file. First, because a VHMap uses a C++
  325. array internally, and because C++ array slots are initialized
  326. differently than single elements, you must ensure that class Person
  327. contains (1) a no-argument constructor, and (2) an assigment operator.
  328. You could arrange this via
  329.  
  330.      class Person
  331.      { ...;
  332.          Person() {}
  333.        void operator = (const Person& p) { nm = p.nm; addr = p.addr; }
  334.      };
  335.  
  336.    (The lack of action in the constructor is OK here because `Strings'
  337. posess usable no-argument constructors.)
  338.  
  339.    You also need to edit `Person.defs.h' to indicate a usable hash
  340. function and default capacity, via something like
  341.  
  342.      #include <builtin.h>
  343.      #define <T>HASH(x)  (hashpjw(x.name().chars()))
  344.      #define DEFAULT_INITIAL_CAPACITY 1000
  345.  
  346.    Since the `hashpjw' function from `builtin.h' is appropriate here.
  347. Changing the default capacity to a value expected to exceed the actual
  348. capacity helps to avoid "hidden" inefficiencies when a new VHMap is
  349. created without overriding the default, which is all too easy to do.
  350.  
  351.    Otherwise, everything is the same as above, substituting `VHMap' for
  352. `AVLMap'.
  353.  
  354. 
  355. File: libgpp,  Node: Representations,  Next: Expressions,  Prev: Proto,  Up: Top
  356.  
  357. Variable-Sized Object Representation
  358. ************************************
  359.  
  360.    One of the first goals of the GNU C++ library is to enrich the kinds
  361. of basic classes that may be considered as (nearly) "built into" C++. A
  362. good deal of the inspiration for these efforts is derived from
  363. considering features of other type-rich languages, particularly Common
  364. Lisp and Scheme. The general characteristics of most class and friend
  365. operators and functions supported by these classes has been heavily
  366. influenced by such languages.
  367.  
  368.    Four of these types, Strings, Integers, BitSets, and BitStrings (as
  369. well as associated and/or derived classes) require representations
  370. suitable for managing variable-sized objects on the free-store. The
  371. basic technique used for all of these is the same, although various
  372. details necessarily differ from class to class.
  373.  
  374.    The general strategy for representing such objects is to create
  375. chunks of memory that include both header information (e.g., the size
  376. of the object), as well as the variable-size data (an array of some
  377. sort) at the end of the chunk. Generally the maximum size of an object
  378. is limited to something less than all of addressable memory, as a
  379. safeguard. The minimum size is also limited so as not to waste
  380. allocations expanding very small chunks. Internally, chunks are
  381. allocated in blocks well-tuned to the performance of the `new' operator.
  382.  
  383.    Class elements themselves are merely pointers to these chunks. Most
  384. class operations are performed via inline "translation" functions that
  385. perform the required operation on the corresponding representation.
  386. However, constructors and assignments operate by copying entire
  387. representations, not just pointers.
  388.  
  389.    No attempt is made to control temporary creation in expressions and
  390. functions involving these classes. Users of previous versions of the
  391. classes will note the disappearance of both "Tmp" classes and reference
  392. counting. These were dropped because, while they did improve
  393. performance in some cases, they obscure class mechanics, lead
  394. programmers into the false belief that they need not worry about such
  395. things, and occaisionally have paradoxical behavior.
  396.  
  397.    These variable-sized object classes are integrated as well as
  398. possible into C++. Most such classes possess converters that allow
  399. automatic coercion both from and to builtin basic types. (e.g., char*
  400. to and from String, long int to and from Integer, etc.). There are
  401. pro's and con's to circular converters, since they can sometimes lead
  402. to the conversion from a builtin type through to a class function and
  403. back to a builtin type without any special attention on the part of the
  404. programmer, both for better and worse.
  405.  
  406.    Most of these classes also provide special-case operators and
  407. functions mixing basic with class types, as a way to avoid constructors
  408. in cases where the operations do not rely on anything special about the
  409. representations.  For example, there is a special case concatenation
  410. operator for a String concatenated with a char, since building the
  411. result does not rely on anything about the String header. Again, there
  412. are arguments both for and against this approach. Supporting these cases
  413. adds a non-trivial degree of (mainly inline) function proliferation, but
  414. results in more efficient operations. Efficiency wins out over parsimony
  415. here, as part of the goal to produce classes that provide sufficient
  416. functionality and efficiency so that programmers are not tempted to try
  417. to manipulate or bypass the underlying representations.
  418.  
  419. 
  420. File: libgpp,  Node: Expressions,  Next: Pix,  Prev: Representations,  Up: Top
  421.  
  422. Some guidelines for using expression-oriented classes
  423. *****************************************************
  424.  
  425.    The fact that C++ allows operators to be overloaded for user-defined
  426. classes can make programming with library classes like `Integer',
  427. `String', and so on very convenient. However, it is worth becoming
  428. familiar with some of the inherent limitations and problems associated
  429. with such operators.
  430.  
  431.    Many operators are *constructive*, i.e., create a new object based
  432. on some function of some arguments. Sometimes the creation of such
  433. objects is wasteful. Most library classes supporting expressions
  434. contain facilities that help you avoid such waste.
  435.  
  436.    For example, for `Integer a, b, c; ...;  c = a + b + a;', the plus
  437. operator is called to sum a and b, creating a new temporary object as
  438. its result. This temporary is then added with a, creating another
  439. temporary, which is finally copied into c, and the temporaries are then
  440. deleted. In other words, this code might have an effect similar to
  441. `Integer a, b, c; ...; Integer t1(a); t1 += b; Integer t2(t1); t2 += a;
  442. c = t2;'.
  443.  
  444.    For small objects, simple operators, and/or non-time/space critical
  445. programs, creation of temporaries is not a big problem. However, often,
  446. when fine-tuning a program, it may be a good idea to rewrite such code
  447. in a less pleasant, but more efficient manner.
  448.  
  449.    For builtin types like ints, and floats, C and C++ compilers already
  450. know how to optimize such expressions to reduce the need for
  451. temporaries. Unfortunately, this is not true for C++ user defined
  452. types, for the simple (but very annoying, in this context) reason that
  453. nothing at all is guaranteed about the semantics of overloaded operators
  454. and their interrelations. For example, if the above expression just
  455. involved ints, not Integers, a compiler might internally convert the
  456. statement into something like ` c += a; c += b; c+= a; ', or perhaps
  457. something even more clever.  But since C++ does not know that Integer
  458. operator += has any relation to Integer operator +, A C++ compiler
  459. cannot do this kind of expression optimization itself.
  460.  
  461.    In many cases, you can avoid construction of temporaries simply by
  462. using the assignment versions of operators whenever possible, since
  463. these versions create no temporaries. However, for maximum flexibility,
  464. most classes provide a set of "embedded assembly code" procedures that
  465. you can use to fully control time, space, and evaluation strategies.
  466. Most of these procedures are "three-address" procedures that take two
  467. `const' source arguments, and a destination argument. The procedures
  468. perform the appropriate actions, placing the results in the destination
  469. (which is may involve overwriting old contents). These procedures are
  470. designed to be fast and robust. In particular, aliasing is always
  471. handled correctly, so that, for example `add(x, x, x); ' is perfectly
  472. OK. (The names of these procedures are listed along with the classes.)
  473.  
  474.    For example, suppose you had an Integer expression ` a = (b - a) *
  475. -(d / c); '
  476.  
  477.    This would be compiled as if it were ` Integer t1=b-a; Integer
  478. t2=d/c; Integer t3=-t2; Integer t4=t1*t3; a=t4;'
  479.  
  480.    But, with some manual cleverness, you might yourself some up with `
  481. sub(a, b, a); mul(a, d, a); div(a, c, a); '
  482.  
  483.    A related phenomenon occurs when creating your own constructive
  484. functions returning instances of such types. Suppose you wanted to
  485. write function `Integer f(const Integer& a) { Integer r = a;  r += a;
  486. return r; }'
  487.  
  488.    This function, when called (as in ` a = f(a); ') demonstrates a
  489. similar kind of wasted copy. The returned value r must be copied out of
  490. the function before it can be used by the caller. In GNU C++, there is
  491. an alternative via the use of named return values. Named return values
  492. allow you to manipulate the returned object directly, rather than
  493. requiring you to create a local inside a function and then copy it out
  494. as the returned value. In this example, this can be done via `Integer
  495. f(const Integer& a) return r(a) { r += a; return; }'
  496.  
  497.    A final guideline: The overloaded operators are very convenient, and
  498. much clearer to use than procedural code. It is almost always a good
  499. idea to make it right, *then* make it fast, by translating expression
  500. code into procedural code after it is known to be correct.
  501.  
  502. 
  503. File: libgpp,  Node: Pix,  Next: Headers,  Prev: Expressions,  Up: Top
  504.  
  505. Pseudo-indexes
  506. **************
  507.  
  508.    Many useful classes operate as containers of elements. Techniques for
  509. accessing these elements from a container differ from class to class.
  510. In the GNU C++ library, access methods have been partially standardized
  511. across different classes via the use of pseudo-indexes called `Pixes'. 
  512. A `Pix' acts in some ways like an index, and in some ways like a
  513. pointer. (Their underlying representations are just `void*' pointers).
  514. A `Pix' is a kind of "key" that is translated into an element access by
  515. the class.  In virtually all cases, `Pixes' are pointers to some kind
  516. internal storage cells. The containers use these pointers to extract
  517. items.
  518.  
  519.    `Pixes' support traversal and inspection of elements in a collection
  520. using analogs of array indexing. However, they are pointer-like in that
  521. `0' is treated as an invalid `Pix', and unsafe insofar as programmers
  522. can attempt to access nonexistent elements via dangling or otherwise
  523. invalid `Pixes' without first checking for their validity.
  524.  
  525.    In general it is a very bad idea to perform traversals in the the
  526. midst of destructive modifications to containers.
  527.  
  528.    Typical applications might include code using the idiom
  529.      for (Pix i = a.first(); i != 0; a.next(i)) use(a(i));
  530.    for some container `a' and function `use'.
  531.  
  532.    Classes supporting the use of `Pixes' always contain the following
  533. methods, assuming a container `a' of element types of `Base'.
  534.  
  535. `Pix i = a.first()'
  536.      Set i to index the first element of a or 0 if a is empty.
  537.  
  538. `a.next(i)'
  539.      advance i to the next element of a or 0 if there is no next
  540.      element;
  541.  
  542. `Base x = a(i); a(i) = x;'
  543.      a(i) returns a reference to the element indexed by i.
  544.  
  545. `int present = a.owns(i)'
  546.      returns true if Pix i is a valid Pix in a. This is often a
  547.      relatively slow operation, since the collection must usually
  548.      traverse through elements to see if any correspond to the Pix.
  549.  
  550.    Some container classes also support backwards traversal via
  551.  
  552. `Pix i = a.last()'
  553.      Set i to the last element of a or 0 if a is empty.
  554.  
  555. `a.prev(i)'
  556.      sets i to the previous element in a, or 0 if there is none.
  557.  
  558.    Collections supporting elements with an equality operation possess
  559.  
  560. `Pix j = a.seek(x)'
  561.      sets j to the index of the first occurrence of x, or 0 if x is not
  562.      contained in a.
  563.  
  564.    Bag classes possess
  565.  
  566. `Pix j = a.seek(x, Pix from = 0)'
  567.      sets j to the index of the next occurrence of x following i, or 0
  568.      if x is not contained in a. If i == 0, the first occurrence is
  569.      returned.
  570.  
  571.    Set, Bag, and PQ classes possess
  572.  
  573. `Pix j = a.add(x) (or a.enq(x) for priority queues)'
  574.      add x to the collection, returning its Pix. The Pix of an item can
  575.      change in collections where further additions and deletions
  576.      involve the actual movement of elements (currently in OXPSet,
  577.      OXPBag, XPPQ, VOHSet), but in all other cases, an item's Pix may
  578.      be considered a permanent key to its location.
  579.  
  580. 
  581. File: libgpp,  Node: Headers,  Next: Builtin,  Prev: Pix,  Up: Top
  582.  
  583. Header files for interfacing C++ to C
  584. *************************************
  585.  
  586.    The following files are provided so that C++ programmers may invoke
  587. common C library and system calls. The names and contents of these
  588. files are subject to change in order to be compatible with the
  589. forthcoming GNU C library. Other files, not listed here, are simply
  590. C++-compatible interfaces to corresponding C library files.
  591.  
  592. `values.h'
  593.      A collection of constants defining the numbers of bits in builtin
  594.      types, minimum and maximum values, and the like. Most names are
  595.      the same as those found in `values.h' found on Sun systems.
  596.  
  597. `std.h'
  598.      A collection of common system calls and `libc.a' functions. Only
  599.      those functions that can be declared without introducing new type
  600.      definitions (socket structures, for example) are provided. Common
  601.      `char*' functions (like `strcmp') are among the declarations. All
  602.      functions are declared along with their library names, so that
  603.      they may be safely overloaded.
  604.  
  605. `string.h'
  606.      This file merely includes `<std.h>', where string function
  607.      prototypes are declared. This is a workaround for the fact that
  608.      system `string.h' and `strings.h' files often differ in contents.
  609.  
  610. `osfcn.h'
  611.      This file merely includes `<std.h>', where system function
  612.      prototypes are declared.
  613.  
  614. `libc.h'
  615.      This file merely includes `<std.h>', where C library function
  616.      prototypes are declared.
  617.  
  618. `math.h'
  619.      A collection of prototypes for functions usually found in libm.a,
  620.      plus some `#define'd constants that appear to be consistent with
  621.      those provided in the AT&T version. The value of `HUGE' should be
  622.      checked before using. Declarations of all common math functions
  623.      are preceded with `overload' declarations, since these are
  624.      commonly overloaded.
  625.  
  626. `stdio.h'
  627.      Declaration of `FILE' (`_iobuf'), common macros (like `getc'), and
  628.      function prototypes for `libc.a' functions that operate on
  629.      `FILE*''s. The value `BUFSIZ' and the declaration of `_iobuf'
  630.      should be checked before using.
  631.  
  632. `assert.h'
  633.      C++ versions of assert macros.
  634.  
  635. `generic.h'
  636.      String concatenation macros useful in creating generic classes.
  637.      They are similar in function to the AT&T CC versions.
  638.  
  639. `new.h'
  640.      Declarations of the default global operator new, the two-argument
  641.      placement version, and associated error handlers.
  642.  
  643. 
  644. File: libgpp,  Node: Builtin,  Next: New,  Prev: Headers,  Up: Top
  645.  
  646. Utility functions for built in types
  647. ************************************
  648.  
  649.    Files `builtin.h' and corresponding `.cc' implementation files
  650. contain various convenient inline and non-inline utility functions.
  651. These include useful enumeration types, such as `TRUE', `FALSE' ,the
  652. type definition for pointers to libg++ error handling functions, and
  653. the following functions.
  654.  
  655. `long abs(long x); double abs(double x);'
  656.      inline versions of abs. Note that the standard libc.a version,
  657.      `int abs(int)' is *not* declared as inline.
  658.  
  659. `void clearbit(long& x, long b);'
  660.      clears the b'th bit of x (inline).
  661.  
  662. `void setbit(long& x, long b);'
  663.      sets the b'th bit of x (inline)
  664.  
  665. `int testbit(long x, long b);'
  666.      returns the b'th bit of x (inline).
  667.  
  668. `int even(long y);'
  669.      returns true if x is even (inline).
  670.  
  671. `int odd(long y);'
  672.      returns true is x is odd (inline).
  673.  
  674. `int sign(long x); int sign(double x);'
  675.      returns -1, 0, or 1, indicating whether x is less than, equal to,
  676.      or greater than zero (inline).
  677.  
  678. `long gcd(long x, long y);'
  679.      returns the greatest common divisor of x and y.
  680.  
  681. `long lcm(long x, long y);'
  682.      returns the least common multiple of x and y.
  683.  
  684. `long lg(long x);'
  685.      returns the floor of the base 2 log of x.
  686.  
  687. `long pow(long x, long y); double pow(double x, long y);'
  688.      returns x to the integer power y using via the iterative O(log y)
  689.      "Russian peasant" method.
  690.  
  691. `long sqr(long x); double sqr(double x);'
  692.      returns x squared (inline).
  693.  
  694. `long sqrt(long y);'
  695.      returns the floor of the square root of x.
  696.  
  697. `unsigned int hashpjw(const char* s);'
  698.      a hash function for null-terminated char* strings using the method
  699.      described in Aho, Sethi, & Ullman, p 436.
  700.  
  701. `unsigned int multiplicativehash(int x);'
  702.      a hash function for integers that returns the lower bits of
  703.      multiplying x by the golden ratio times pow(2, 32). See Knuth, Vol
  704.      3, p 508.
  705.  
  706. `unsigned int foldhash(double x);'
  707.      a hash function for doubles that exclusive-or's the first and
  708.      second words of x, returning the result as an integer.
  709.  
  710. `double start_timer()'
  711.      Starts a process timer.
  712.  
  713. `double return_elapsed_time(double last_time)'
  714.      Returns the process time since last_time. If last_time == 0
  715.      returns the time since the last start_timer. Returns -1 if
  716.      start_timer was not first called.
  717.  
  718.    File `Maxima.h' includes versions of `MAX, MIN' for builtin types.
  719.  
  720.    File `compare.h' includes versions of `compare(x, y)' for buitlin
  721. types. These return negative if the first argument is less than the
  722. second, zero for equal, and positive for greater.
  723.  
  724. 
  725. File: libgpp,  Node: New,  Next: IOStream,  Prev: Builtin,  Up: Top
  726.  
  727. Library dynamic allocation primitives
  728. *************************************
  729.  
  730.    Libg++ contains versions of `malloc, free, realloc' that were
  731. designed to be well-tuned to C++ applications. The source file
  732. `malloc.c' contains some design and implementation details. Here are
  733. the major user-visible differences from most system malloc routines:
  734.  
  735.   1. These routines *overwrite* storage of freed space. This means that
  736.      it is never permissible to use a `delete''d object in any way.
  737.      Doing so will either result in trapped fatal errors or random
  738.      aborts within malloc, free, or realloc.
  739.  
  740.   2. The routines tend to perform well when a large number of objects
  741.      of the same size are allocated and freed. You may find that it is
  742.      not worth it to create your own special allocation schemes in such
  743.      cases.
  744.  
  745.   3. The library sets top-level `operator new()' to call malloc and
  746.      `operator delete()' to call free. Of course, you may override these
  747.      definitions in C++ programs by creating your own operators that
  748.      will take precedence over the library versions. However, if you do
  749.      so, be sure to define *both* `operator new()' and `operator
  750.      delete()'.
  751.  
  752.   4. These routines do *not* support the odd convention, maintained by
  753.      some versions of malloc, that you may call `realloc' with a pointer
  754.      that has been `free''d.
  755.  
  756.   5. The routines automatically perform simple checks on `free''d
  757.      pointers that can often determine whether users have accidentally
  758.      written beyond the boundaries of allocated space, resulting in a
  759.      fatal error.
  760.  
  761.   6. The function `malloc_usable_size(void* p)' returns the number of
  762.      bytes actually allocated for `p'. For a valid pointer (i.e., one
  763.      that has been `malloc''d or `realloc''d but not yet `free''d) this
  764.      will return a number greater than or equal to the requested size,
  765.      else it will normally return 0. Unfortunately, a non-zero return
  766.      can not be an absolutely perfect indication of lack of error. If a
  767.      chunk has been `free''d but then re-allocated for a different
  768.      purpose somewhere elsewhere, then `malloc_usable_size' will return
  769.      non-zero. Despite this, the function can be very valuable for
  770.      performing run-time consistency checks.
  771.  
  772.   7. `malloc' requires 8 bytes of overhead per allocated chunk, plus a
  773.      mmaximum alignment adjustment of 8 bytes. The number of bytes of
  774.      usable space is exactly as requested, rounded to the nearest 8
  775.      byte boundary.
  776.  
  777.   8. The routines do *not* contain any synchronization support for
  778.      multiprocessing. If you perform global allocation on a shared
  779.      memory multiprocessor, you should disable compilation and use of
  780.      libg++ malloc in the distribution `Makefile' and use your system
  781.      version of malloc.
  782.  
  783.  
  784. 
  785. File: libgpp,  Node: IOStream,  Next: Stream,  Prev: New,  Up: Top
  786.  
  787. The new input/output classes
  788. ****************************
  789.  
  790.    The iostream classes implement most of the features of AT&T version
  791. 2.0 iostream library classes, and most of the features of the ANSI
  792. X3J16 library draft (which is based on the AT&T design). The iostream
  793. classes replace all of the old stream classes in previous versions of
  794. libg++.  It is not totally compatible, so you will probably need to
  795. change your code in places.
  796.  
  797. The `streambuf' layer
  798. =====================
  799.  
  800.    The lower level abstraction is the `streambuf' layer. A `streambuf'
  801. (or one of the classes derived from it) implements a character source
  802. and/or sink, usually with buffering.
  803.  
  804.    Classes derived from `streambuf' include:
  805.    * A `filebuf' is used for reading and writing from files.
  806.  
  807.    * A `strstreambuf' can raed and write from a string in main memory.
  808.      The string buffer will be re-allocated as needed it, unless it is
  809.      "frozen".
  810.  
  811.    * An `indirectbuf' just forwards all read/write requests to some
  812.      other buffer.
  813.  
  814.    * A `procbuf' can read from or write to a Unix process.
  815.  
  816.    * A `parsebuf' has some useful features for scanning text:  It keeps
  817.      track of line and column numbers, and it guarantees to remember at
  818.      least the current line (with the linefeeds at either end), so you
  819.      can arbitrarily backup within that time.  WARNING:  The interface
  820.      is likely to change.
  821.  
  822.    * An `edit_streambuf' reads and writes into a region of an
  823.      `edit_buffer' called an `edit_string'.  Emacs-like marks are
  824.      supported, and sub-strings are first-class functions.  WARNING: The
  825.      interface is almost certain to change.
  826.  
  827. The istream and ostream classes
  828. ===============================
  829.  
  830.    The stream layer provides an efficient, easy-to-use, and type-secure
  831. interface between C++ and an underlying `streambuf'.
  832.  
  833.    Most C++ textbooks will at least given an overview of the stream
  834. classes.  Some libg++ specifics:
  835. `istream::get(char* s, int maxlength, char terminator='\n')'
  836.      Behaves as described by Stroustrup. It reads at most maxlength
  837.      characters into s, stopping when the terminator is read, and
  838.      pushing the terminator back into the input stream.
  839.  
  840. `istream::getline(char* s, int maxlength, char terminator = '\n')'
  841.      Behaves like get, except that the terminator is read (and not
  842.      pushed back), though it does not become part of the string.
  843.  
  844. `istream::gets(char** ss, char terminator = '\n')'
  845.      reads in a line (as in get) of unknown length, and places it in a
  846.      free-store allocated spot and attaches it to `ss'. The programmer
  847.      must take responsibility for deleting `*ss' when it is no longer
  848.      needed.
  849.  
  850. `ostream::form(const char* format...)'
  851.      outputs `printf'-formated data.
  852.  
  853. The SFile class
  854. ===============
  855.  
  856.    `SFile' (short for structure file) is provided both as a
  857. demonstration of how to build derived classes from `iostream', and as a
  858. useful class for processing files containing fixed-record-length binary
  859. data.  They are created with constructors with one additional argument
  860. declaring the size (in bytes, i.e., `sizeof' units) of the records. 
  861. `get', will input one record, `put' will output one, and the `[]'
  862. operator, as in `f[i]', will position to the i'th record. If the file
  863. is being used mainly for random access, it is often a good idea to
  864. eliminate internal buffering via `setbuf' or `raw'. Here is an example:
  865.  
  866.      class record
  867.      {
  868.        friend class SFile;
  869.        char c; int i; double d;     // or anything at all
  870.      };
  871.      
  872.      void demo()
  873.      {
  874.        record r;
  875.        SFile recfile("mydatafile", sizeof(record), ios::in|ios::out);
  876.        recfile.raw();
  877.        for (int i = 0; i < 10; ++i)  // ... write some out
  878.        {
  879.          r = something();
  880.          recfile.put(&r);            // use '&r' for proper coercion
  881.        }
  882.        for (i = 9; i >= 0; --i)      // now use them in reverse order
  883.        {
  884.          recfile[i].get(&r);
  885.          do_something_with(r);
  886.        }
  887.      }
  888.  
  889. The PlotFile Class
  890. ==================
  891.  
  892.    Class `PlotFile' is a simple derived class of `ofstream' that may be
  893. used to produce files in Unix plot format.  Public functions have names
  894. corresponding to those in the `plot(5)' manual entry.
  895.  
  896. C standard I/O
  897. ==============
  898.  
  899.    There is a complete implementation of the ANSI C stdio library that
  900. is built on *top* of the iostream facilities. Specifically, the type
  901. `FILE' is the same as the `streambuff' class. Also, the standard files
  902. are identical to the standard streams: `stdin == cin.rdbuf()'.  This
  903. means that you don't have to synchronize C++ output with C output.  It
  904. also means that C programs can use some of the specialized sub-classes
  905. of streambuf.
  906.  
  907.    The stdio library (`libstdio++')is not normally installed, because
  908. of some difficulties when used with the C libraries version of stdio.
  909. The stdio library provides binary compatibility with traditional
  910. implementation.  Unfortunately, it takes a fair amount of care to avoid
  911. duplicate definitions when linking with both `libstdio++' and the C
  912. library.
  913.  
  914. 
  915. File: libgpp,  Node: Stream,  Next: Obstack,  Prev: IOStream,  Up: Top
  916.  
  917. The old I/O library
  918. *******************
  919.  
  920.    WARNING: This chapter describes classes that are *obsolete*. These
  921. classes are normally not available when libg++ is installed normally. 
  922. The sources are currently included in the distribution, and you can
  923. configure libg++ to use these classes instead of the new iostream
  924. classes. This is only a temporary measure; you should convert your code
  925. to use iostreams as soon as possible.  The iostream classes provide
  926. some compatibility support, but it is very incomplete (there is no
  927. longer a `File' class).
  928.  
  929. File-based classes
  930. ==================
  931.  
  932.    The `File' class supports basic IO on Unix files.  Operations are
  933. based on common C stdio library functions.
  934.  
  935.    `File' serves as the base class for istreams, ostreams, and other
  936. derived classes. It contains the interface between the Unix stdio file
  937. library and these more structured classes.  Most operations are
  938. implemented as simple calls to stdio functions. `File' class operations
  939. are also fully compatible with raw system file reads and writes (like
  940. the system `read' and `lseek' calls) when buffering is disabled (see
  941. below). The `FILE*' stdio file pointer is, however maintained as
  942. protected. Classes derived from File may only use the IO operations
  943. provided by File, which encompass essentially all stdio capabilities.
  944.  
  945.    The class contains four general kinds of functions: methods for
  946. binding `File's to physical Unix files, basic IO methods, file and
  947. buffer control methods, and methods for maintaining logical and
  948. physical file status.
  949.  
  950.    Binding and related tasks are accomplished via `File' constructors
  951. and destructors, and member functions `open, close, remove, filedesc,
  952. name, setname'.
  953.  
  954.    If a file name is provided in a constructor or open, it is
  955. maintained as class variable `nm' and is accessible via `name'.  If no
  956. name is provided, then `nm' remains null, except that `Files' bound to
  957. the default files stdin, stdout, and stderr are automatically given the
  958. names `(stdin), (stdout), (stderr)' respectively. The function
  959. `setname' may be used to change the internal name of the `File'. This
  960. does not change the name of the physical file bound to the File.
  961.  
  962.    The member function `close' closes a file.  The `~File' destructor
  963. closes a file if it is open, except that stdin, stdout, and stderr are
  964. flushed but left open for the system to close on program exit since
  965. some systems may require this, and on others it does not matter. 
  966. `remove' closes the file, and then deletes it if possible by calling the
  967. system function to delete the file with the name provided in the `nm'
  968. field.
  969.  
  970. Basic IO
  971. ========
  972.  
  973.    * `read' and `write' perform binary IO via stdio `fread' and
  974.      `fwrite'.
  975.  
  976.    * `get' and `put' for chars invoke stdio `getc' and `putc' macros.
  977.  
  978.    * `put(const char* s)' outputs a null-terminated string via stdio
  979.      `fputs'.
  980.  
  981.    * `unget' and `putback' are synonyms.  Both call stdio `ungetc'.
  982.  
  983. File Control
  984. ============
  985.  
  986.    `flush', `seek', `tell', and `tell' call the corresponding stdio
  987. functions.
  988.  
  989.    `flush(char)' and `fill()' call stdio `_flsbuf' and `_filbuf'
  990. respectively.
  991.  
  992.    `setbuf' is mainly useful to turn off buffering in cases where
  993. nonsequential binary IO is being performed. `raw' is a synonym for
  994. `setbuf(_IONBF)'.  After a `f.raw()', using the stdio functions instead
  995. of the system `read, write', etc., calls entails very little overhead. 
  996. Moreover, these become fully compatible with intermixed system calls
  997. (e.g., `lseek(f.filedesc(), 0, 0)'). While intermixing `File' and
  998. system IO calls is not at all recommended, this technique does allow
  999. the `File' class to be used in conjunction with other functions and
  1000. libraries already set up to operate on file descriptors. `setbuf'
  1001. should be called at most once after a constructor or open, but before
  1002. any IO.
  1003.  
  1004. File Status
  1005. ===========
  1006.  
  1007.    File status is maintained in several ways.
  1008.  
  1009.    A `File' may be checked for accessibility via `is_open()', which
  1010. returns true if the File is bound to a usable physical file,
  1011. `readable()', which returns true if the File can be read from (opened
  1012. for reading, and not in a _fail state), or `writable()', which returns
  1013. true if the File can be written to.
  1014.  
  1015.    `File' operations return their status via two means: failure and
  1016. success are represented via the logical state. Also, the return values
  1017. of invoked stdio and system functions that return useful numeric values
  1018. (not just failure/success flags) are held in a class variable
  1019. accessible via `iocount'. (This is useful, for example, in determining
  1020. the number of items actually read by the `read' function.)
  1021.  
  1022.    Like the AT&T i/o-stream classes, but unlike the description in the
  1023. Stroustrup book, p238, `rdstate()' returns the bitwise OR of `_eof',
  1024. `_fail' and `_bad', not necessarily distinct values. The functions
  1025. `eof()', `fail()', `bad()', and `good()' can be used to test for each of
  1026. these conditions independently.
  1027.  
  1028.    `_fail' becomes set for any input operation that could not read in
  1029. the desired data, and for other failed operations. As with all Unix IO,
  1030. `_eof' becomes true only when an input operations fails because of an
  1031. end of file. Therefore, `_eof' is not immediately true after the last
  1032. successful read of a file, but only after one final read attempt. Thus,
  1033. for input operations, `_fail' and `_eof' almost always become true at
  1034. the same time.  `bad' is set for unbound files, and may also be set by
  1035. applications in order to communicate input corruption. Conversely,
  1036. `_good' is defined as 0 and is returned by `rdstate()' if all is well.
  1037.  
  1038.    The state may be modified via `clear(flag)', which, despite its
  1039. name, sets the corresponding state_value flag. `clear()' with no
  1040. arguments resets the state to `_good'. `failif(int cond)' sets the
  1041. state to `_fail' only if `cond' is true.
  1042.  
  1043.    Errors occuring during constructors and file opens also invoke the
  1044. function `error'.  `error' in turn calls a resetable error handling
  1045. function pointed to by the non-member global variable
  1046. `File_error_handler' only if a system error has been generated. Since
  1047. `error' cannot tell if the current system error is actually responsible
  1048. for a failure, it may at times print out spurious messages. Three error
  1049. handlers are provided. The default, `verbose_File_error_handler' calls
  1050. the system function `perror' to print the corresponding error message
  1051. on standard error, and then returns to the caller. 
  1052. `quiet_File_error_handler' does nothing, and simply returns. 
  1053. `fatal_File_error_handler' prints the error and then aborts execution.
  1054. These three handlers, or any other user-defined error handlers can be
  1055. selected via the non-member function `set_File_error_handler'.
  1056.  
  1057.    All read and write operations communicate either logical or physical
  1058. failure by setting the `_fail' flag.  All further operations are
  1059. blocked if the state is in a `_fail' or`_bad' condition. Programmers
  1060. must explicitly use `clear()' to reset the state in order to continue
  1061. IO processing after either a logical or physical failure.  C
  1062. programmers who are unfamiliar with these conventions should note that,
  1063. unlike the stdio library, `File' functions indicate IO success, status,
  1064. or failure solely through the state, not via return values of the
  1065. functions.  The `void*' operator or `rdstate()' may be used to test
  1066. success.  In particular, according to c++ conversion rules, the `void*'
  1067. coercion is automatically applied whenever the `File&' return value of
  1068. any `File' function is tested in an `if' or `while'.  Thus, for
  1069. example, an easy way to copy all of stdin to stdout until eof (at which
  1070. point `get' fails) or some error is `char c; while(cin.get(c) &&
  1071. cout.put(c));'.
  1072.  
  1073.    The current version of istreams and ostreams differs significantly
  1074. from previous versions in order to obtain compatibility with AT&T 1.2
  1075. streams. Most code using previous versions should still work. However,
  1076. the following features of `File' are not incorporated in streams (they
  1077. are still present in `File'): `scan(const char* fmt...), remove(),
  1078. read(), write(), setbuf(), raw()'. Additionally, the feature of
  1079. previous streams that allowed free intermixing of stream and stdio
  1080. input and output is no longer guaranteed to always behave as desired.
  1081.  
  1082.