是否在静态内存中创建С++中的字符串文字? [英] Is a string literal in С++ created in static memory?

查看:50
本文介绍了是否在静态内存中创建С++中的字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++中的字符串文字是否在静态内存中创建并且仅在程序退出时销毁?

Is a string literal in c++ created in static memory and destroyed only when the program exits?

推荐答案

创建它的地方实际上是编译器编写者的实现决定.字符串文字很可能会存储在只读的内存段中,因为它们永远不会改变.

Where it's created is an implementation decision by the compiler writer, really. Most likely, string literals will be stored in read-only segments of memory since they never change.

在旧的编译器时代,您曾经拥有像这些文字这样的静态数据以及全局但可变的数据.这些分别存储在TEXT(代码)段和DATA(初始化数据)段中.

In the old compiler days, you used to have static data like these literals, and global but changeable data. These were stored in the TEXT (code) segment and DATA (initialised data) segment.

即使您具有像 char * x ="hello"; 这样的代码, hello 字符串本身也会存储在只读存储器中,而变量 x在堆栈上(如果是全局的,则在可写内存中的其他位置). x 只是设置为 hello 字符串的地址.这样就可以进行诸如字符串折叠之类的各种棘手的事情,以便无效选项"(0x1000)和有效选项"(0x1002)可以使用相同的内存块,如下所示:

Even when you have code like char *x = "hello";, the hello string itself is stored in read-only memory while the variable x is on the stack (or elsewhere in writeable memory if it's a global). x just gets set to the address of the hello string. This allows all sorts of tricky things like string folding, so that "invalid option" (0x1000) and "valid option" (0x1002) can use the same memory block as follows:

+-> plus:0   1   2   3   4   5   6   7   8   9   A   B   C   D   E
|      +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+
0x1000 | i | n | v | a | l | i | d |   | o | p | t | i | o | n | \0 |
       +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+

请记住,我并不是说就ROM而言,只读存储器,而是专用于存储不可更改内容的存储器(操作系统可能会将其标记为真正的只读存储器).

Keep in mind I don't mean read-only memory in terms of ROM, just memory that's dedicated to storing unchangeable stuff (which may be marked really read-only by the OS).

它们也永远不会被破坏,直到 main()退出.

They're also never destroyed until main() exits.

这篇关于是否在静态内存中创建С++中的字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆