开发者

Any Disadvantage to using String (C++)

I actually checked on google开发者_如何学Go for this but I usually found the reverse. Is there actual any disadvantage in C++ to using the string library strings instead of C strings or some kind of character arrays? besides maybe being a bit slower?

Feel free to point me to a dupe, however I've searched and couldn't find anything (altho im sure someone has asked)


There's really no significant disadvantage, assuming the vendor implementation of std::string is competent. The std::string class is not likely to be any slower than plain C-strings with compiler optimizations turned on.

Even if you find yourself in a situation where you need a C string (like say, you need to work with an API that takes a const char*), you always have std::string::c_str().

One possible disadvantage you might run into is vendor implementations that implement COW semantics in a non-thread-safe manner. (See std::string in a multi-threaded program)

However, this will be a non-issue in C++0x, and even in C++03 it's really an example of a problematic vendor implementation rather than anything inherently wrong with std::string.

Another possible disadvantage is the fact that there is some debate as to whether the wording in the C++03 standard requires an std::string implementation to use a contiguous memory buffer. This makes it somewhat questionable whether or not you can do things like read directly from a file into an std::string object. However, it's easy to argue that the C++03 standard does, in fact, implicitly require a contiguous buffer, and anyway it's mostly an academic matter because in practice 1) most (or all) implementations of std::string in fact do provide a contiguous buffer, and 2) the problem is moot for C++0x, which explicitly requires a contiguous buffer.


The only possible case I can think of is when you need to handle really huge strings (say, some mega/gigabytes). In that case, you need to do quite a few tricks to avoid copying and to implement placement new if STL string class is chosen. The char arrays will be much straightforward for manipulations like that.


EDIT

Sorry, I completely mis-understood your question. As for disadvantages, I believe some implementations of the string class use reference counting, which can lead to unexpected performance characteristics when it comes to multi-threaded applications.


IMHO The answer depends on what you're doing. If you rely on outside libraries that use C Strings, by all means use C Strings.

Or... Maybe you have a complete C String library you've used for years...

Otherwise I'd use the stdlib strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜