为什么在std字符串中间设置null没有任何效果

Che*_*eng 3 c++ stdstring

考虑

#include <string>
#include <iostream>

int main()
{
    /*
    hello
    5
    hel
    3
    */
    char a[] = "hello";
    std::cout << a << std::endl;
    std::cout << strlen(a) << std::endl;
    a[3] = 0;
    std::cout << a << std::endl;
    std::cout << strlen(a) << std::endl;

    /*
    hello
    5
    hel o
    5
    */
    std::string b = "hello";
    std::cout << b << std::endl;
    std::cout << b.length() << std::endl;
    b[3] = 0;
    std::cout << b << std::endl;
    std::cout << b.length() << std::endl;

    getchar();

}
Run Code Online (Sandbox Code Playgroud)

我希望它的std::string行为与char数组a 相同.就是这样,在字符串中间插入空字符,将"终止"字符串.但事实并非如此.我的期望是错的吗?

Gre*_*ill 9

A std::string不像通常的C字符串,并且可以包含嵌入的NUL字符而不会出现问题.但是,如果您这样做,您会注意到如果您使用该.c_str()函数返回a ,字符串会提前终止const char *.