为什么它返回一个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/