Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::string provide implicit conversion to char*?

Tags:

c++

string

stl

std::string provides const char* c_str ( ) const which:

Get C string equivalent

Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

Why don't they just define operator const char*() const {return c_str();}?

like image 283
Dustin Getz Avatar asked Jan 29 '09 15:01

Dustin Getz


People also ask

Can you convert string to char in C++?

The c_str() and strcpy() function in C++C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').

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.

Why do we use string instead of char?

std::string is almost always preferred. Even for speed, it uses small array on the stack before dynamically allocating more for larger strings. However, char* pointers are still needed in many situations for writing strings/data into a raw buffer (e.g. network I/O), which can't be done with std::string.

Why do we use char instead of string in C++?

The main reason for using const char* is because it is compatible and linkable with C. Many APIs and other libraries have C interfaces (you use the API via a collection of C-like functions).


1 Answers

From the C++ Programming Language 20.3.7 (emphasis mine):

Conversion to a C-style string could have been provided by an operator const char*() rather than c_str(). This would have provided the convenience of an implicit conversion at the cost of surprises in cases in which such a conversion was unexpected.

like image 75
user7116 Avatar answered Sep 16 '22 18:09

user7116