Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator char* in STL string class

Tags:

c++

stl

Why doesn't the STL string class have an overloaded char* operator built-in? Is there any specific reason for them to avoid it?

If there was one, then using the string class with C functions would become much more convenient.

I would like to know your views.

like image 524
Pallavi Avatar asked Aug 17 '09 07:08

Pallavi


People also ask

Is char * a string?

char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

Should I use std::string or * char?

Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.

What does char * mean in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.


1 Answers

Following is the quote from Josuttis STL book:

However, there is no automatic type conversion from a string object to a C-string. This is for safety reasons to prevent unintended type conversions that result in strange behavior (type char* often has strange behavior) and ambiguities (for example, in an expression that combines a string and a C-string it would be possible to convert string into char* and vice versa). Instead, there are several ways to create or write/copy in a C-string, In particular, c_str() is provided to generate the value of a string as a C-string (as a character array that has '\0' as its last character).

like image 102
Naveen Avatar answered Oct 02 '22 07:10

Naveen