On Jun 1, 8:12 pm, Ian Collins <ian-n...@hotmail.co mwrote:
Javier wrote:
Hello,
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). 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).
So for the original poster's question, const char* will always be
portable and is safe to use in a library interface, 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. YMMV.
--
Computational Fluid Dynamics, CSIRO (CMIS)
Melbourne, Australia