WvStreams
wvstringex.cc
1/*
2 * A WvString example.
3 *
4 * Some text about this example...
5 */
6#include "wvstring.h"
7#include <stdio.h>
8#include <assert.h>
9
10int main()
11{
12 const char *mystring = "Cool!";
13
14 // Creates x as a wrapper for mystring
15 WvStringParm x(mystring);
16 // ...x's internal string buffer points to mystring
17 assert(x.cstr() == mystring);
18 assert(strcmp(x, mystring) == 0);
19
20 // Creates y as a copy of mystring
21 WvString y(mystring);
22 // ...y's internal string buffer points to a copy of mystring
23 assert(y.cstr() != mystring);
24 assert(strcmp(y, mystring) == 0);
25
26 // Creates z as a copy of y
27 WvString z(y);
28 // ...z's internal string buffer points to y's
29 assert(z.cstr() == y.cstr());
30 // ...prove it by modifying y
31 // (dangerous use of const_cast<>, see below for example of edit())
32 const_cast<char*>(y.cstr())[0] = 'Z'; // change first char to Z
33 assert(z.cstr()[0] == 'Z');
34 // ...and make it point to a unique copy of the string
35 z.unique(); // could also write z.edit()
36 assert(z.cstr() != y.cstr());
37 // ...prove it by modifying y again
38 const_cast<char*>(y.cstr())[0] = 'Y'; // change first char to Y
39 assert(z.cstr()[0] == 'Z'); // but z points to a different string
40
41 // Notice that cstr() deliberately returns a const char* to make
42 // it hard to accidentally modify an internal string buffer that
43 // is shared by multiple WvStrings. That is why the use of edit()
44 // is preferred. This automatically performs unique() then returns
45 // a non-const pointer to the internal string buffer.
46 // Consider:
47 WvString w(z);
48 // ...w's internal string buffer points to z's
49 assert(w.cstr() == z.cstr());
50 // ...but not anymore
51 w.edit()[0] = 'W';
52 assert(w.cstr() != z.cstr());
53 assert(w.cstr()[0] == 'W');
54 assert(z.cstr()[0] == 'Z');
55
56 puts("Success!");
57 return 0;
58}
A WvFastString acts exactly like a WvString, but can take (const char *) strings without needing to a...
Definition: wvstring.h:94
WvString is an implementation of a simple and efficient printable-string class.
Definition: wvstring.h:330