在这里,我有两行代码
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 * s1或char 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)
const char * s1 = "test";
char s2 [] = "test";
Run Code Online (Sandbox Code Playgroud)
这两者并不完全相同.s1是不可变的:它指向恒定的记忆.修改字符串文字是未定义的行为.
是的,在C++中你应该更喜欢std::string.