c++ - 指向 const char 与 char 数组与 std::string 的指针

标签 c++

这里有两行代码

const char * s1 = "test";
char s2 [] = "test";

两行代码具有相同的行为,所以我看不出我应该更喜欢 s1 而不是 s2 还是相反。除了s1和s2,还有使用std::string的方式。我认为使用 std::string 的方式是最优雅的。在查看其他代码时,我经常看到人们使用 const char *char s []。因此,我现在的问题是,什么时候应该使用 const char * s1char s []std::string?有什么区别,在什么情况下我应该使用哪种方法?

最佳答案

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

关于c++ - 指向 const char 与 char 数组与 std::string 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393291/

相关文章:

c++ - 在不同源文件中声明的相同名称类没有编译器/链接器错误

c++ - 获取 IAMStreamConfig 接口(interface)失败

c++ - 何时在 C++ 中调用要移动到的对象的析构函数?

android - GLES 错误 : vertex attribute array is enabled with no data bound

c++ - 有没有办法启动没有可执行文件扩展名的可执行文件?

c++ - 尽管显式转换,类变量仍被隐式转换为 int

C++ 套接字 - 使用新行发送消息 (linux)

c++ - 在 Visual Studio 2010 C/C++ 中, "Rescan Solution"操作的作用是什么?

c++ - 在 C++11 中初始化 C 字符串?

c++ - 新手 : Performance Analysis through the command line