c++ - 为什么 string::c_str() 在动态分配字符串时返回 const char*?

标签 c++ string char constants

为什么它返回一个constant char指针? C++11 标准说:

The pointer returned points to the internal array currently used by the string object to store the characters that conform its value.

动态分配的东西怎么可能是常量(const char*)?

最佳答案

在 C 和 C++ 中,const 或多或少地转换为“只读”。

所以,当某个东西返回一个 char const * 时,这并不一定意味着它指向的数据实际上是 const——它只是意味着你的指针'receiving 只支持读,不支持它指向的数据。

字符串对象本身可能能够修改该数据——但是(至少通过您收到的指针)您不能直接修改数据。

关于c++ - 为什么 string::c_str() 在动态分配字符串时返回 const char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65430224/

相关文章:

C# PHP 样式数组键

C++:按制表符拆分字符串,但包含空格

c - 如何对包含数字和字符的UTF-8字符串进行排序?

C++ 从一个字符中获取指定的部分

c - 获取 char* 的子串

c++ - 使用 QProcess 读取标准输出

c++ - 什么是损坏的 MPEG 流?

c++ - 将数据从 C++ 传递到 gnuplot 示例(使用 Gnuplot-iostream 接口(interface))

c++ - 如何在 3D 场景中使用和设置轴

Char数组声明问题