为什么是字符串常量const? [英] Why are string literals const?

查看:123
本文介绍了为什么是字符串常量const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已知在C ++中,字符串文字是不可变的,修改字符串文字的结果是未定义的。例如

It is known that in C++ string literals are immutable and the result of modifying a string literal is undefined. For example

char * str = "Hello!";
str[1] = 'a';

这将导致未定义的行为。

This will bring to an undefined behavior.

此外,字符串字面量放置在静态内存中。所以他们存在于整个程序。我想知道为什么字符串字面量有这样的属性。

Besides that string literals are placed in static memory. So they exists during whole program. I would like to know why do string literals have such properties.

推荐答案

有几个不同的原因。

以允许将字符串文字存储在只读存储器中(如其他人已经提到的那样)。

One is to allow storing string literals in read-only memory (as others have already mentioned).

另一个是允许合并字符串文字。如果一个程序在几个不同的地方使用相同的字符串字面量,那么允许(但不一定要求)编译器合并它们是很好的,所以你可以获得多个指向同一内存的指针,而不是每个占用单独的内存块。这也适用于两个字符串字面值不一定相同,但具有相同的结尾:

Another is to allow merging of string literals. If one program uses the same string literal in several different places, it's nice to allow (but not necessarily require) the compiler to merge them, so you get multiple pointers to the same memory, instead of each occupying a separate chunk of memory. This can also apply when two string literals aren't necessarily identical, but do have the same ending:

char *foo = "long string";
char *bar = "string";

在这种情况下, bar

In a case like this, it's possible for bar to be foo+5 (if I'd counted correctly).

在任何一种情况下,我们都可以使用 foo + 5 如果允许修改字符串文字,它可以修改恰好具有相同内容的其他字符串文字。与此同时,老实说,在强制要求,这是非常不常见的有足够的字符串文字,你可以重叠,大多数人可能希望编译器运行较慢只是为了保存(可能)几十个字节

In either of these cases, if you allow modifying a string literal, it could modify the other string literal that happens to have the same contents. At the same time, there's honestly not a lot of point in mandating that either -- it's pretty uncommon to have enough string literals that you could overlap that most people probably want the compiler to run slower just to save (maybe) a few dozen bytes or so of memory.

在写第一个标准时,已经有编译器使用了这三种技术(可能还有其他几种)。因为没有办法描述一个修改字符串的行为,没有人显然认为这是一个重要的支持能力,他们做的很明显:说,即使试图这样做导致未定义的行为。

By the time the first standard was written, there were already compilers that used all three of these techniques (and probably a few others besides). Since there was no way to describe one behavior you'd get from modifying a string literal, and nobody apparently thought it was an important capability to support, they did the obvious: said even attempting to do so led to undefined behavior.

这篇关于为什么是字符串常量const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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