我有一个下面的代码片段。我期待输出将是 mystring ,但奇怪的是它输出垃圾字符。

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
    string s1("mystring");

    const char* s2 = s1.c_str();

    s1 = "Hi there, this is a changed string s1";

    cout << s2 << endl;

    return 0;
}

(1)
我最初的想法是 c_str 负责分配足够的内存
保存 s1 并返回分配给 s2 的内存块的地址,从这里 s1s2 独立开始。

(2)
但是当我分配 s1 = "Hi there ..... " 时,我在(1)中的想法被证明是错误的。不知何故, s1 仍在影响 s2

(3)
当我注释掉 s1 = "Hi there .... " 行时,一切正常,即 mystring 得到一致打印。

(4)
我不太相信我在 (1) 中的说法,即 c_str 正在分配内存来保存 s1 ,因为如果是这种情况,我们将不得不通过 s2 指针来处理释放该内存块,而我们不这样做。所以我不确定。

请帮我解释这种奇怪的行为。

最佳答案

s1.c_str() 不返回独立于 s1 的内存。 s1 的更改使 s1.c_str() 返回的指针无效。

换句话说,要小心使用 c_str 。通常使用它将 C 字符串传递给不接受 C++ 字符串的函数。

关于c++ - c_str 的奇怪行为?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51893685/

10-11 22:59
查看更多