Topic: string conversion to char*
Author: "Nathan Myers, http://www.cantrip.org/" <ncm@cantrip.org>
Date: 1996/04/02 Raw View
Andrew Bell wrote:
>
> Kresimir Fresl <fresl@master.grad.hr> wrote:
> >According to proposed standard one should write:
> > ifstream (file_name.c_str());
> >because implicit conversion of string to const char* is not defined.
> >
> >I agree that implicit conversion is (almost always) dangerous, and I
> >_do not_ propose to add conversion operator to string class.
> Is there an explanation for why implicit conversion (at least to char
> *) is dangerous? It doesn't seem to me that requiring the member
> function call is that much safer, although admittedly it is easier to
> grep for. However, the added complexity of code w/o a conversion
> operator seems like it would add almost as many problems.
Member c_str() is safer because the person who calls it knows it
is being called. The problem with implicit conversions is less that
they are hard to grep for, but rather that they are often invoked
accidentally and invisibly.
If an implicit conversion were provided, the pointer would inevitably
be passed to contexts in which its limited lifetime would not be kept
track of, resulting in unreliable programs. It would be nearly impossible
to find these bugs, because the cause of the bug literally does not appear
in the code.
The extra text ".cstr()" does not add to complexity; the complexity is
present regardless. It only makes the complexity visible.
Nathan Myers
ncm@cantrip.org http://www.cantrip.org/
---
[ comp.std.c++ is moderated. To submit articles: Try just posting with your
newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
Comments? mailto:std-c++-request@ncar.ucar.edu
]