我用的是visual studio 2017
int main()
{
std::string a = "hello";
std::cout << &a;
a[1] = 'r';
std::cout << &a; gives same address as above
std::cin.get();
}
当我将鼠标指针悬停在“你好”上时。
它显示 const char[6]。所以“你好”存储在只读内存中。
那怎么可以改变里面的值。
最佳答案
where string literals will be stored
字符串文字具有静态存储持续时间。
then how come it is possible to change the value in it.
您没有更改字符串文字(这是在 C++ 中无法完成的事情)。
您已经创建了一个std::string
类型的对象。 std::string
包含一个(可能)动态分配的缓冲区。您已将字符串文字复制到该动态缓冲区中,并且正在修改字符串文字的拷贝。
But with "hrllo".It should allocate new memory for "hrllo" right? and make a to point to new location?
没有。修改 std::string
的字符不会导致重新分配。但是,插入字符可能可能导致重新分配。
关于c++ - 字符串文字将存储在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54984177/