ai didi

c++ - 字符串文字将存储在哪里

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:26 24 4
gpt4 key购买 nike

我用的是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]。所以“你好”存储在只读内存中。

那怎么可以改变里面的值。

screen shot

最佳答案

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/

24 4 0
文章推荐: c++ - 如何在声明和定义中拆分静态 lambda?
文章推荐: android - 在移动应用程序上添加语音搜索功能
文章推荐: html - CSS 右对齐顺序错误
文章推荐: c++ - 模板声明是否仅适用于它们之前立即声明的函数
太空宇宙
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com