为什么 a 和 b 在下面的代码中共享相同的地址

Why do a and b share the same address in the following code?

本文关键字:共享 地址 代码 在下面 为什么      更新时间:2023-10-16

为什么在这种情况下会触发静态断言?由于 64 位地址行和 char 是单个字节,它们是否位于同一地址?

  #include <type_traits>
    int main()
    {
      char a='a';
      char b='b';
      static_assert ( &a == &b, " ERROR: Same addr"  ) ;
    }
    main.cpp: In function ‘int main()’:
    main.cpp:9:3: error: static assertion failed:  ERROR: Same addr

你的逻辑倒过来了。 static_assert在条件为false时触发,即两个对象没有相同的地址。

ab位于不同的地址。你的断言是错误的。您的断言失败,因为两个地址不同。尝试

static_assert ( &a != &b, " ERROR: Same addr"  ) ;