Efficiency of C-String vs C++Strings

前端 未结 8 664
忘掉有多难
忘掉有多难 2020-12-28 14:20

C++ Primer says

For most applications, in addition to being safer, it is also more efficient to use library strings rather then C-style strings

相关标签:
8条回答
  • 2020-12-28 14:51

    Here is a short point of view.

    First of all, C++ strings are objects, so it is more consistent to use them in an object oriented language.

    Then, the standard library comes with a lot of useful functions for strings, iterators, etc. All this stuff is stuff you won't have to code again, so you gain time and you're sure that this code is (almost) bugless.

    Finally, C strings are pointers, that are kind of difficult to understant when you're new, and they bring complexity. Since references are preferred over pointers in C++, it makes more sens e to use std::string instead of C string.

    Hope i helped.

    0 讨论(0)
  • 2020-12-28 14:52

    Strings are the object which contain character arrays within themselves along with their size and other functionalities.It is better to use strings from strings library because they save you from allocating and deallocating memory, looking out for memory leaks and other pointer hazards. But as strings are objects, so they take extra space in memory.

    Cstrings are simply character arrays. They SHOULD be used when you are working in real time; when you do not know completely about how much memory space you have in hand. If you are using cstrings, you would have to take care for memory allocation, then copying data into it via strcpy or character by character, then deallocating after its usage, etc,etc. So better use strings from string library if you want to avoid a bunch of head aches.

    Strings increase program efficiency but reduce processing efficiency(though not necessarily). Vice versa is with cstrings

    0 讨论(0)
提交回复
热议问题