WvStreams
|
00001 /* 00002 * A WvString example. 00003 * 00004 * Some text about this example... 00005 */ 00006 #include "wvstring.h" 00007 #include <stdio.h> 00008 #include <assert.h> 00009 00010 int main() 00011 { 00012 const char *mystring = "Cool!"; 00013 00014 // Creates x as a wrapper for mystring 00015 WvStringParm x(mystring); 00016 // ...x's internal string buffer points to mystring 00017 assert(x.cstr() == mystring); 00018 assert(strcmp(x, mystring) == 0); 00019 00020 // Creates y as a copy of mystring 00021 WvString y(mystring); 00022 // ...y's internal string buffer points to a copy of mystring 00023 assert(y.cstr() != mystring); 00024 assert(strcmp(y, mystring) == 0); 00025 00026 // Creates z as a copy of y 00027 WvString z(y); 00028 // ...z's internal string buffer points to y's 00029 assert(z.cstr() == y.cstr()); 00030 // ...prove it by modifying y 00031 // (dangerous use of const_cast<>, see below for example of edit()) 00032 const_cast<char*>(y.cstr())[0] = 'Z'; // change first char to Z 00033 assert(z.cstr()[0] == 'Z'); 00034 // ...and make it point to a unique copy of the string 00035 z.unique(); // could also write z.edit() 00036 assert(z.cstr() != y.cstr()); 00037 // ...prove it by modifying y again 00038 const_cast<char*>(y.cstr())[0] = 'Y'; // change first char to Y 00039 assert(z.cstr()[0] == 'Z'); // but z points to a different string 00040 00041 // Notice that cstr() deliberately returns a const char* to make 00042 // it hard to accidentally modify an internal string buffer that 00043 // is shared by multiple WvStrings. That is why the use of edit() 00044 // is preferred. This automatically performs unique() then returns 00045 // a non-const pointer to the internal string buffer. 00046 // Consider: 00047 WvString w(z); 00048 // ...w's internal string buffer points to z's 00049 assert(w.cstr() == z.cstr()); 00050 // ...but not anymore 00051 w.edit()[0] = 'W'; 00052 assert(w.cstr() != z.cstr()); 00053 assert(w.cstr()[0] == 'W'); 00054 assert(z.cstr()[0] == 'Z'); 00055 00056 puts("Success!"); 00057 return 0; 00058 }