为什么在动态分配字符串时 string::c_str() return 是 const char*?

Why does string::c_str() return a const char* when strings are allocated dynamically?

为什么它 return 是一个 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 或多或少翻译为“只读”。

所以,当某些东西 returns 变成 char const * 时,这并不一定意味着它指向的数据实际上是 const——它只是意味着你所指向的指针receiving只支持读,不支持写它指向的数据

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

c_str 返回的指针声明为指向 const char 以防止通过该指针修改内部 string 缓冲区。

string缓冲区确实是动态分配的,c_str返回的指针只有在字符串本身不发生变化时才有效。引用自 cppreference.com:

The pointer obtained from c_str() may be invalidated by:

  • Passing a non-const reference to the string to any standard library function, or

  • Calling non-const member functions on the string, excluding operator[], at(), front(), back(), begin(), rbegin(), end() and rend().

我将把这个问题解释为为什么你不能将它转换回 char * 并写入它并期望它工作。

标准库为自己保留了在复制构造函数中延迟复制字符串的选项;因此,如果您通过 c_str() 的结果写入它,您可能会写入其他字符串。由于 c_str() 的大多数使用不需要写入字符串,因此对 c_str() 的调用进行重复数据删除会造成太大的惩罚。