Topic: Why no conversion of string to const char


Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/08/02
Raw View
In article 95Aug1200815@toad.scripps.edu, bashford@toad.scripps.edu (Don &) writes:
>According to Plauger's book on the Draft Standard C++ library,
>there is no "operator const char *" for the string class.
>This means that you cannot do things like,
>
>  string filename;
>  // ...
>  ofstream ofile(filename);
>
>Alot of my code has things like this (I have been using the
>String class of libg++) and I suspect this is rather common
>apparently we will all have to change to:
>
>  ofstream ofile(filename.c_str());
>
>which will be incompatable with any other string class that
>does not have a c_str function (String of libg++ does not).
>
>Is there any compelling reason for not having the conversion
>to const char* as part of the standard?

For the first part of your question, the C++ committee is discussing
whether the fstream member functions should accept a string parameter
as well as char* parameters. It seems reasonable to do so.

For your last question, yes it is a deliberate design decision not to
have an "operator char*" conversion function. Type conversion operators
are dangerous, since you may get conversions where you don't expect or
want them. In the specific case of "operator char*" for a string, it exposes
the internal data member, and the pointer can become invalid after calling
any non-const member function on that string. If the char* conversion
happened when you didn't expect it, you could wind up trying to use an
invalid pointer when you thought you were using a string.

Instead, you must use a named function to convert a string to a char*. The
compiler will never insert an implicit call to a named function, as it
will insert an implicit type conversion where ever needed. The c_str function
has an explicit warning about invalid pointers as part of its specification.

---
Steve Clamage, stephen.clamage@eng.sun.com