next up previous contents
Next: Stack-based string data Up: Allocation Options Previous: Allocation Options   Contents

Subsections

Heap-based string data

Heap based string data can be used via any of the following functions:

Initialize with char* data

One easy way to create string data is to initialize the data with a char* string. For example:

// One way
Str x("Hello");

// A second way
Str x = "Hello";

// A third way
char* str = "Hello";
Str x(str);

// A fourth way
char* str = "Hello";
Str x = str;

Note that all of the above functions actually call the same constructor, the second and forth examples are using the special-case copy-constructor that C++ provides. These examples allocate a new data buffer on the heap and copy the string data into it. Note that, due to the copy, the original data is left alone, even if the string is modified.

Construct from another string

A string constructed from another string will get its own data area, allocated by default on the heap.

x = Str("Hello")

//One way
Str y(x);

// Another way
Str z = x;

Construct an empty string of a specified size

Instead of specifying an initialization string, you can construct a string by giving an initial heap size. You can also specify if a string is time efficient. This is a convenient way to create a string buffer that will be used to hold a large amount of data.

// Create a 32k string buffer that is time-efficient
Str buff(32768, 1);

You can also create a string based on your own heap data. This will be explained further in the next chapter.

char* buff1 = malloc(32768);
char* buff2 = malloc(16384);
strcpy(buff2, "Hello");

// Create and initialize a string from my buffer and take 
// ownership of it (free it when finished with it)
Str x(buff1, 32768, true, true);

// Create a string using the given buffer data, do not initialize
// the data.  I will keep responsibility for freeing the buffer
Str y(buff2, 16384, false, false)


next up previous contents
Next: Stack-based string data Up: Allocation Options Previous: Allocation Options   Contents
2007-05-05