PTypes: string: constructors/destructors

Top: Basic types: string: Constructors/destructors

>     #include <ptypes.h>

>     class string {
>         string();
>         string(const string&);
>         string(char);
>         string(const char*);
>         string(const char*, int);
>         ~string();
>     }

A string object can be constructed in 5 different ways:

- default constructor string() creates an empty string.

- copy constructor string(const string& s) creates a copy of the given string s. Actually this constructor only increments the reference count by 1 and no memory allocation takes place.

- string(char c) constructs a new string consisting of one character c.

- string(const char* s) constructs a new string object from a null-terminated string. If s is either NULL or is a pointer to a null character, an empty string object is created. This constructor can be used to assign a string literal to a string object (see examples below).

- string(const char* s, int len) copies len bytes of data from buffer s to the newly allocated string buffer.

Destructor ~string() decrements the reference count for the given string buffer and removes it from the dynamic memory if necessary.

Examples:

>     string s1;             // empty string
>     string s2 = s1;        // copy
>     string s3 = 'A';       // single character
>     string s4 = "ABCabc";  // string literal
>     char* p = "ABCabc";
>     string s5 = p;         // null-terminated string
>     string s6(p, 3);       // buffer/length

See also: Operators, Typecasts, Manipulation, Conversion

PTypes home