Top: Basic types: string: Typecasts

>     #include <ptypes.h>

>     class string {
>         operator (const char*)() const;
>     }

A string object can be assigned to a variable or passed as an actual parameter of type const char* implicitly (by default). Such assignments should be used carefully, since the library does not keep track of whether a char pointer refers to the given string buffer. To make sure that a char pointer refers to a valid string buffer, always make the scope of a char pointer variable smaller than or equal to the scope of a string object. In most cases passing a string object to a system or API call is safe (see examples below). This typecast operator does not perform any actions and simply returns a pointer to the string buffer.

The value of the char pointer is guaranteed to be non-NULL. Even if the string is empty, the char pointer will refer to a null-symbol.

A string buffer can not be modified through a constant char pointer. If you want to modify the string buffer through a char pointer, use unique(string&) function instead. This function always returns a reference to a unique string buffer (i.e. when the reference count is 1).

Compatibility note: MSVC and GCC may treat type casts in different ways when passing a string object to a function that takes (...) parameters, e.g. printf() or outstm::putf(). You should explicitly instruct the compiler to cast the string object to (const char*) to avoid this problem. PTypes provides a shorter typedef pconst for this.

Examples

>     void assignment_example()
>     {
>        string s = "abcdef";
>        const char* p = s;
>        // do string manipulation here...
>     }

>     void function_call_example()
>     {
>        string s = "abcdef";
>        puts(s);
>        printf("%s\n", pconst(s));
>     }

See also: Constructors/destructors, Operators, Manipulation, Conversion

PTypes home