home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / libgpp.i02 (.txt) < prev    next >
GNU Info File  |  1993-06-12  |  49KB  |  863 lines

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