Re: const char* vs string
On Jun 3, 2:44 pm, Craig Scott <audiofana...@gmail.com> wrote:
On Jun 1, 8:12 pm, Ian Collins <ian-n...@hotmail.com> wrote:
Javier wrote:
in which cases is it better the use of "const char*" to "string" (or
even const string &).
Seldom.
The only real reason is interfacing with C code.
Actually, it can also matter for C++ code. If you are using shared
libraries, then you need to be aware that the C++ standard does not
guarantee that std::string is safe to use anywhere in a shared
library's interface (it mentions absolutely nothing about shared
libraries at all).
Strictly speaking, that's true for int as well. If all you're
counting on is what the C++ standard says, then you can't count
on int working in a dynamically linked object either.
This is frequently a surprise to many C++
developers, but Scott Meyers and others give this topic a good
treatment in their various books (sorry, I don't have them on hand at
the moment, but one of the Effective C++/STL books I think). In short,
unless you can guarantee that your code is being compiled with exactly
the same compiler version as the library you are calling and that you
are using exactly the same compiler flags, then the only types safe to
use in the shared library's interface are POD types and pointers (but
it would be potentially unsafe to dereference these pointers).
Not even that: you can't be sure at all about any struct, since
padding may depend on compiler options. For that matter, you
can't be sure about long---I've had the byte order of a long
change from one version of the compiler to the next, and you
certainly can't be sure about pointers, whose size depends on
compiler options.
In practice, there will be a set of options you can play with,
over a set of versions of the compiler.
So for the original poster's question, const char* will always be
portable and is safe to use in a library interface,
Except when the size of a pointer depends on a compiler option
(the usual case today, where all of the platforms I know support
both 32 and 64 bit pointers).
In fact, you're never really portable. The library supplier
should specify the restrictions, but in general, using
std::string entails no more risk than using any other struct.
whereas
std::string might or might not be safe depending on the compiler and
flags used. In real world code, we've found that this does matter and
we have defined our interfaces accordingly.
In the real world, we use std::string and std::vector without
problems, over a variety of compilers and systems.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34