Why should one use std::string over c-style strings in C++?

后端 未结 6 2018
慢半拍i
慢半拍i 2020-12-15 23:36

\"One should always use std::string over c-style strings(char *)\" is advice that comes up for almost every source code posted here. While the

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 00:16

    Well, if you just need an array of chars, std::string provides little advantage. But face it, how often is that the case? By wrapping a char array with additional functionality like std::string does, you gain both power and efficiency for some operations.

    For example, determining the length of an array of characters requires "counting" the characters in the array. In contrast, an std::string provides an efficient operation for this particular task. (see https://stackoverflow.com/a/1467497/129622)

    1. For power, efficiency and sanity
    2. Larger memory footprint than "just" a char array
    3. When you just need an array of chars

提交回复
热议问题