views:

126

answers:

5

Hi,

my question is simple:
Should I use array of char eg:

char *buf, buf2[MAX_STRING_LENGTH]

etc or should I use std::string in a library that will be used by other programmers where they can use it on any SO and compiler of their choice?

Considering performance and portability...

from my point of view, std strings are easier and performance is equal or the difference is way too little to not use std:string, about portability I don't know. I guess as it is standard, there shouldn't be any compiler that compiles C++ without it, at least any important compiler.

EDIT:
The library will be compiled on 3 major OS and, theorically, distributed as a lib

Your thoughts?

ty,
Joe

+5  A: 

Depends on how this library will be used in conjunction with client code. If it will be linked in dynamically and you have a set of APIs exposed for the client -- you are better off using null terminated byte strings (i.e. char *) and their wide-character counterparts. If you are talking about using them within your code, you certainly are free to use std::string. If it is going to be included in source form -- std::string works fine.

dirkgently
Sorry, I couldn't completely undrstand your post. So I should expose char* and use string internally for easyness purpose?
Jonathan
Yes, that is what I meant.
dirkgently
+1  A: 

I would recommend just using std::string. Besides if you want compatibility with libraries requiring C-style strings (for example, which uses a C compatible API), you can always just use the c_str() method of std::string.

catchmeifyoutry
+2  A: 

But if your library is shipped as DLL your users will have to use the same implementation of std::string. It won't be possible for them to use STLPort (or any other implementation) if your library was built using Microsoft STL.

Nikola Smiljanić
this causes me no end of problems in MySQL ...
Goz
+2  A: 

As long as you are targetting pure C++ for your library, using std::string is fine and even desirable. However, doing that ties you to a particular implementation of C++ (the one used to build your library), and it can't be linked with other C++ implementations or other languages.

Often, it is highly desirable to give a library a C interface rather than a C++ one. That way its usable by any other language that provides a C foreign function interface (which is most of them). For a C interface, you need to use char *

Chris Dodd
A: 

In general, you will be better off using std::string, certainly for calls internal to your library.

For your API, it's dependent on what its purpose is. For internal use within your organization, an API that uses std::string will probably be fine. For external use you may wish to provide a C API, one which uses char*

Liz Albin