const char与char数组vs std :: string的指针

Sys*_*ata 9 c++

在这里,我有两行代码

const char * s1 = "test";
char s2 [] = "test";
Run Code Online (Sandbox Code Playgroud)

这两行代码具有相同的行为,所以我看不出是否应该优先选择s1,s2反之亦然.除了s1和s2之外,还有使用方式std::string.我认为使用std :: string的方式是最优雅的.在查看其他代码时,我经常看到人们use const char *或者char s [].因此,我现在的问题是,我应该何时使用const char * s1char s []std::string?有什么区别,我应该在哪种情况下使用哪种方法?

Lig*_*ica 11

POINTERS
--------

char const* s1 = "test";  // pointer to string literal - do not modify!

char* s1       = "test";  // pointer to string literal - do not modify!
                          //   (conversion to non-const deprecated in C++03 and
                          //       disallowed in C++11)

ARRAYS
------

char s1[5]     = "test";  // mutable character array copied from string literal
                          //    - do what you like with it!

char s1[]      = "test";  // as above, but with size deduced from initialisation



CLASS-TYPE OBJECTS
------------------

std::string s1 = "test";  // C++ string object with data copied from string
                          //    literal - almost always what you *really* want
Run Code Online (Sandbox Code Playgroud)


Luc*_*ore 9

const char * s1 = "test";
char s2 [] = "test";
Run Code Online (Sandbox Code Playgroud)

这两者并不完全相同.s1是不可变的:它指向恒定的记忆.修改字符串文字是未定义的行为.

是的,在C++中你应该更喜欢std::string.

  • @ System.Data:作为一个更通用的协议,你应该**总是**使用`const`,除非你知道你不想要...而不是相反.这是一个根植于向后兼容性的设计缺陷,C++名称默认为可变而不是不可变. (5认同)