Re: c-style string vs std::string
Christopher <cpisz@austin.rr.com> wrote:
I am growing really tired of having to decypher 1000 functions that
were written to do simple operations on c-style strings that I could
do in 50 lines with streams and std::strings. My peer uses that same
old ,"Its more efficient " argument that I always hear.
The efficiency depends on a lot of things.
For example, if you only use static arrays of type char as your strings
(which are thus always allocated on the stack and never change size), then
they will be faster than using std::string (which will always allocate
memory on the heap).
The same is true for class members. Certainly "class A { char str[30]; };"
will be significantly more efficient than "class A { std::string std; };"
with a constructor that sets the 'str' to be of size 30 (the class in
question will be faster to instantiate, copy and destroy).
Of course even then it depends on how much those strings are being
allocated and destroyed. If this happens very rarely, then the difference
becomes negligible.
If the C strings are being allocated, resized and freed constantly, then
it becomes more complicated. It depends on how and how much, and what kind
of operations are being applied to them, etc...
If the difference is small or even negligible, then the modularity and
safety provided by std::string becomes a crucial factor. This will not only
reduce the amount of bugs, but in many cases it will make the code shorter,
simpler and easier to understand.
In fact, that
argument has grown into ,"we shouldn't use any of the STL containers,
because they allocate, which is expensive."
And what exactly is the proposed alternative?