Jonathan
Jonathan

Reputation: 4918

Array of char or std::string for a public library?

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?

Upvotes: 2

Views: 407

Answers (5)

Liz Albin
Liz Albin

Reputation: 1489

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*

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126140

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 *

Upvotes: 2

Nikola Smiljanić
Nikola Smiljanić

Reputation: 26873

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.

Upvotes: 3

catchmeifyoutry
catchmeifyoutry

Reputation: 7349

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.

Upvotes: 1

dirkgently
dirkgently

Reputation: 111120

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.

Upvotes: 5

Related Questions