为什么(仅)某些编译器对相同的字符串文字使用相同的地址? [英] Why do (only) some compilers use the same address for identical string literals?

查看:118
本文介绍了为什么(仅)某些编译器对相同的字符串文字使用相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://godbolt.org/z/cyBiWY

我可以在MSVC生成的汇编代码中看到两个'some'文字,但是只有一个带有clang和gcc.这导致代码执行的结果完全不同.

I can see two 'some' literals in assembler code generated by MSVC, but only one with clang and gcc. This leads to totally different results of code execution.

static const char *A = "some";
static const char *B = "some";

void f() {
    if (A == B) {
        throw "Hello, string merging!";
    }
}

谁能解释这些编译输出之间的区别和相似之处?为什么即使不要求优化,clang/gcc也会优化某些内容?这是某种不确定的行为吗?

Can anyone explain the difference and similarities between those compilation outputs? Why does clang/gcc optimize something even when no optimizations are requested? Is this some kind of undefined behaviour?

我还注意到,如果将声明更改为以下所示,则clang/gcc/msvc根本不会在汇编代码中保留任何"some".为什么行为不同?

I also notice that if I change the declarations to those shown below, clang/gcc/msvc do not leave any "some" in the assembler code at all. Why is the behaviour different?

static const char A[] = "some";
static const char B[] = "some";

推荐答案

这不是未定义的行为,而是未指定的行为.对于字符串文字

This is not undefined behavior, but unspecified behavior. For string literals,

允许(但不是必需)编译器组合存储以相等或重叠的字符串文字.这意味着相同的字符串文字在通过指针进行比较时可能会相等,也可能会不同.

The compiler is allowed, but not required, to combine storage for equal or overlapping string literals. That means that identical string literals may or may not compare equal when compared by pointer.

这意味着A == B的结果可能是truefalse,您不应依赖它们.

That means the result of A == B might be true or false, on which you shouldn't depend.

根据标准 [lex.string]/16 :

所有字符串文字是否都是不同的(即存储在非重叠对象中),以及字符串字面量的连续求值是产生相同对象还是不同对象都不确定.

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.

这篇关于为什么(仅)某些编译器对相同的字符串文字使用相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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