Article View: comp.std.c++
Article #1549Re: Why no conversion of string to const char
From: Steve Clamage
Date: Wed, 02 Aug 1995 20:13
Date: Wed, 02 Aug 1995 20:13
41 lines
2303 bytes
2303 bytes
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
Technical Details
Message-ID:
<3vom8c$ng4@engnews2.Eng.Sun.COM>Path:
arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!usenetReferences:
<BASHFORD.95Aug1200815@toad.scripps.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!usenet From: clamage@Eng.Sun.COM (Steve Clamage) Newsgroups: comp.std.c++ Subject: Re: Why no conversion of string to const char Date: 2 Aug 1995 20:13:00 GMT Organization: Sun Microsystems Inc. Message-ID: <3vom8c$ng4@engnews2.Eng.Sun.COM> References: <BASHFORD.95Aug1200815@toad.scripps.edu> Reply-To: clamage@Eng.Sun.COM NNTP-Posting-Host: taumet.eng.sun.com