С++ 中的字符串文字是在静态内存中创建的吗?

2021-12-05 00:00:00 string char c++

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 |  |
       +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+

请记住,就 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.

相关文章