Advantages of using user-defined literal for strings instead of string literal

后端 未结 4 1515
野趣味
野趣味 2020-12-29 17:34

The strings topic in the SO Documentation used to say, in the Remarks section:

Since C++14, instead of using \"foo\", it is recommended t

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-29 18:23

    The advice to use "blah"s has nothing to do with efficiency and all to do with correctness for novice code.

    C++ novices who don't have a background in C, tend to assume that "blah" results in an object of some reasonable string type. For example, so that one can write things like "blah" + 42, which works in many script languages. With "blah" + 42 in C++, however, one just incurs Undefined Behavior, addressing beyond the end of the character array.

    But if that string literal is written as "blah"s then one instead gets a compilation error, which is much preferable.

提交回复
热议问题