473,725 Members | 2,168 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 13645
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
6624
by: Hans | last post by:
Hello, Why all C/C++ guys write: const char* str = "Hello"; or const char str = "Hello";
7
4360
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
10101
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
8833
by: Jae | last post by:
Real(const string &fileName) { FILE * myInputFile = fopen(fileName, "rt"); ..... fclose(myInputFile);
3
3223
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
4336
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
2252
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
3558
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
10527
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
3079
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
8888
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9176
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.