home *** CD-ROM | disk | FTP | other *** search
/ Frozen Fish 1: Amiga / FrozenFish-Apr94.iso / bbs / gnu / libg++-2.5.3-bin.lha / info / libg++.info-2 (.txt) < prev    next >
GNU Info File  |  1994-02-27  |  50KB  |  912 lines

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