相关疑难解决方法(0)

为什么(仅)某些编译器对相同的字符串文字使用相同的地址?

https://godbolt.org/z/cyBiWY

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

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

void f() {
    if (A == B) {
        throw "Hello, string merging!";
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释这些编译输出之间的差异和相似之处吗?为什么即使没有请求优化,clang/gcc也会优化某些内容?这是某种未定义的行为吗?

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

static const char A[] = "some";
static const char B[] = "some";
Run Code Online (Sandbox Code Playgroud)

c++ string-literals string-interning language-lawyer

88
推荐指数
3
解决办法
6562
查看次数

c ++相同的字符串不相等(实际上是char*)

我将一个参数传递给我的程序有一个问题,似乎不等于我作为参数放入的内容,除非它们是相同的.将它们变成一个字符串使它们相同,但我想知道为什么最初的二重奏不是.

这是我的代码:

int main(int argc, char *argv[]) {
  if (argc>1) {
    cout << "#" << argv[1] << "#" << endl;
    cout << "#" << "nomast" << "#" << endl;
    cout << (argv[1] == "nomast" ? "equal" : "not equal") << endl;

    string s1 = argv[1];
    string s2 = "nomast";
    cout << (s1 == s2 ? "equal after all" : "nope") << endl;
    system("pause");
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我使用"call thingy.exe nomast"启动已编译的代码时,我得到了输出

#nomast#
#nomast#
not equal
equal after all
Press any key …
Run Code Online (Sandbox Code Playgroud)

c++ pointers

0
推荐指数
1
解决办法
564
查看次数