473,573 Members | 4,503 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const char* vs string

Hello,
in which cases is it better the use of "const char*" to "string" (or
even const string &).
I mean, in STL (http://www.sgi.com/tech/stl/hash_map.html) I see:

hash_map<const char*, int, hash<const char*>, eqstrmonths;
months["january"] = 31;

I think it is for the use in calls like function("my string"), but, is
it really necessary to define funcion(const char*) besides
function(const string &) in my public member functions?

I have read that the compiler does too much temporaries variables in
such cases, but is it true?

And what about in:

string mystring = "my string" + string1 + " is " + string2;

or in:

cout << string << " hello" << string2 << " my name is " << string3;

Thanks.

Jun 1 '07 #1
14 13620
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.
I mean, in STL (http://www.sgi.com/tech/stl/hash_map.html) I see:

hash_map<const char*, int, hash<const char*>, eqstrmonths;
months["january"] = 31;

I think it is for the use in calls like function("my string"), but, is
it really necessary to define funcion(const char*) besides
function(const string &) in my public member functions?

I have read that the compiler does too much temporaries variables in
such cases, but is it true?

And what about in:

string mystring = "my string" + string1 + " is " + string2;

or in:

cout << string << " hello" << string2 << " my name is " << string3;
What about them? I don't see how these link to your question.

--
Ian Collins.
Jun 1 '07 #2
On 1 jun, 12:12, 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.
I mean, in STL (http://www.sgi.com/tech/stl/hash_map.html) I see:
hash_map<const char*, int, hash<const char*>, eqstrmonths;
months["january"] = 31;
I think it is for the use in calls like function("my string"), but, is
it really necessary to define funcion(const char*) besides
function(const string &) in my public member functions?
I have read that the compiler does too much temporaries variables in
such cases, but is it true?
And what about in:
string mystring = "my string" + string1 + " is " + string2;
Does the compiler create temporaries in this case? Is it important? I
mean, is it better to write?:

string mystring = "my string";
mystring += string1;
mystring += " is ";
mystring += string2;

than:

string mystring = "my string" + string1 + " is " + string2;
>
or in:
cout << string << " hello" << string2 << " my name is " << string3;
Same question.
>
What about them? I don't see how these link to your question.

--
Ian Collins.
Thanks.

Jun 1 '07 #3
Javier wrote:
>>
string mystring = "my string" + string1 + " is " + string2;

Does the compiler create temporaries in this case? Is it important? I
mean, is it better to write?:

string mystring = "my string";
mystring += string1;
mystring += " is ";
mystring += string2;

than:

string mystring = "my string" + string1 + " is " + string2;
Yes the second version does create temporaries and additional copies (tho
RVO might reduce some there). However, the second version is clearer than
the first one, seems more natural and unless you do that thousands of times
per second it shouldn't matter the additional cost (ie unless your code
profiling points this as a source of bottleneck). Also I think that in the
future with rvalue references and move semantics that overhead will be
eliminated anyway.

--
Dizzy

Jun 1 '07 #4
Javier wrote:
string mystring = "my string" + string1 + " is " + string2;
Does this even compile? I wouldn't expect it to.
Jun 1 '07 #5
Noah Roberts wrote:
Javier wrote:
>string mystring = "my string" + string1 + " is " + string2;

Does this even compile? I wouldn't expect it to.
Why not? The operator+(const char*, const std::string&) is defined.

Regards,

Zeppe
Jun 1 '07 #6
Javier wrote:
Hello,
in which cases is it better the use of "const char*" to "string" (or
even const string &).
Almost never. The only reason I've ever used it when I needed
read/write access to a fixed-size raw buffer of chars that were
copied across processors using MPI without construction/destruction.

The other reasons could be "to be able to compile the program
with a really ancient C++ compiler which does not recognize string"
and "to show people how nasty bugs appear when using char*" <eg>.

HTH,
- J.
Jun 2 '07 #7
Javier wrote:
in which cases is it better the use of "const char*" to "string" (or
even const string &).
I would say that "const char*" is ok when you really have
compile-time constant strings, especially if you don't really need
to know their size.

Example:

const char* const KEYWORDS[] =
{ "keyword1", "keyword2", "keyword3", ... };

These are just compile-time constants which are not modified during
the execution of the program, so I would say that it's not really
necessary to have them as std::strings. If at some point you really
need to do some handling with those, it's pretty trivial to create
a std::string from them, like: std::string keyword = KEYWORDS[1];

Jun 2 '07 #8
void doSomething(std ::string& param)
{

}
....

doSomething("Do That");

doSomething will certainly call std::string constructor, alloc memory,
copy de contents, deallocate and its destructor will do something else
if it has some reference counter...

Why do that if "DoThat" will be stored in the data segement??? I am
not an expert but I am pretty sure you have a performance overhead
which is the price for the convenience...

So, is it never recommended using [const] char* instead of
std::string? I think "never" should be changed to "never if
performance doesn't matter".

Jose Ricardo
Jun 2 '07 #9
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
Jun 3 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
6575
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
7
4349
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
8
10070
by: andrew.fabbro | last post by:
In a different newsgroup, I was told that a function I'd written that looked like this: void myfunc (char * somestring_ptr) should instead be void myfunc (const char * somestring_ptr) When I asked why, I was told that it facilitated calling it as:
5
8804
by: Jae | last post by:
Real(const string &fileName) { FILE * myInputFile = fopen(fileName, "rt"); ..... fclose(myInputFile);
3
3212
by: dstevel | last post by:
The signature for strtol is: strtol( const char*, char**, int) So.. if we start with a passed "const char*" (pointer to const char), then we can't create a non-const char pointer pointer to that const char pointer as in: void func( const char* a ) {
3
4327
by: Rick Helmus | last post by:
Hello all In a few classes I have overloaded functions for C style strings and STL strings like this class SomeClass { void f(const char *s); void f(const std::string &s); };
2
2238
by: Adrian | last post by:
Hi, In a header file I tried const char *someval="this is a test"; which is included all over the place and I get linker errors about multiple defines. Why is this not folded when const char someval="this is a test"; is and I get no linker errors?
20
3516
by: liujiaping | last post by:
I'm confused about the program below: int main(int argc, char* argv) { char str1 = "abc"; char str2 = "abc"; const char str3 = "abc"; const char str4 = "abc"; const char* str5 = "abc";
9
10512
by: Peithon | last post by:
Hi, This is a very simple question but I couldn't find it in your FAQ. I'm using VC++ and compiling a C program, using the /TC flag. I've got a function for comparing two strings int strspcmp(const char * s1, const char * s2) {
5
3064
by: Bob Doe | last post by:
I have a const static object. What is the right syntax to get a reference to the std::vector within the std::map variable?: class MyObj { public: ... std::map<std::string, std::vector<std::string l_; };
0
7741
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7661
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7977
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7730
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6347
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5252
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2163
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1256
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
984
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.