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

后端 未结 6 2032
慢半拍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:35

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

    The main reason is it frees you from managing the lifetime of the string data. You can just treat strings as values and let the compiler/library worry about managing the memory.

    Manually managing memory allocations and lifetimes is tedious and error prone.

    What are the disadvantages (if any) of the practice mentioned in #1?

    You give up fine-grained control over memory allocation and copying. That means you end up with a memory management strategy chosen by your toolchain vendor rather than chosen to match the needs of your program.

    If you aren't careful you can end up with a lot of unneeded data copying (in a non-refcounted implementation) or reference count manipulation (in a refcounted implementation)

    In a mixed-language project any function whose arguments use std::string or any data structure that contains std::string will not be able to be used directly from other languages.

    What are the scenarios where the opposite of the advice mentioned in #1 is a good practice?

    Different people will have different opinions on this but IMO

    • For function arguments passing strings in "const char *" is a good choice since it avoids unnessacery copying/refcouning and gives the caller flexibility about what they pass in.
    • For things used in interoperation with other languages you have little choice but to use c-style strings.
    • When you have a known length limit it may be faster to use fixed-size arrays.
    • When dealing with very long strings it may be better to use a construction that will definately be refcounted rather than copied (such as a character array wrapped in a shared_ptr) or indeed to use a different type of data structure altogether

提交回复
热议问题