【发布时间】:2019-11-27 05:33:17
【问题描述】:
在编写一些代码时,我遇到了我设置的值设置错误的问题。我最终找到了罪魁祸首,在进行测试时发现它在 C++14 和 C++17 上的行为不同。代码如下:
#include <stdio.h>
#include <cstdint>
#include <cstring>
int main()
{
uint8_t *p = new uint8_t[3];
memset(p, 0x00, 1);
p++;
memset(p, 0xF0, 1);
p++;
memset(p, 0xFF, 1);
p--;
p--;
// This line in particular
*p++ = *p;
*p++ = 0x0F;
p--;
p--;
printf("Position 0 has value %u\n", *p);
p++;
printf("Position 1 has value %u\n", *p);
p++;
printf("Position 2 has value %u\n", *p);
return 0;
}
在 C++14 上打印:
Position 0 has value 240
Position 1 has value 15
Position 2 has value 255
在 C++17 上它会打印:
Position 0 has value 0
Position 1 has value 15
Position 2 has value 255
我很好奇为什么它在不同的 C++ 版本上表现不同。看起来好像在 C++14 上,赋值右侧的 *p 是在 ++ 之后评估的。这改变了吗?而如果++ 有优先权,为什么不在赋值运算符左侧的解引用之前发生呢?
【问题讨论】:
-
未指定您的代码是否编译,因为未指定
#include <stdio.h>后跟#include <cstring>是否将名称memset置于全局范围内。 -
@L.F.我不明白你想说什么
-
@deW1 见stackoverflow.com/q/32606023
-
@deW1 他们说 OP 包含 C++
<cstring>但写了 Cmemset,并且可能无法使用某些工具链编译。 OP 想要<string.h>或std::memset。 (在混合中添加盐是<stdio.h>也可能会传递地引入memset!)