且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可以`mem​​set`函数调用由编译器中删除?

更新时间:2023-11-10 18:41:10

编译器无权假设里面无论发生什么,不会有任何副作用。

"compiler has no right to assume that whatever happens inside it, will have no side effects."

这是正确的。但如果事实上编译器知道什么实际的发生里面并能确定其真正的无副作用,则不需要任何假设。

That's correct. But if the compiler in fact knows what actually happens inside it and can determine that it really has no side effects, then no assumption is needed.

这是所有的编译器优化几乎是如何工作的。在code说:X。编译器确定,如果Y是真的,那么它可以代替codeX与codeZ和不会有任何检测的差异。它决定了Y是真实的,然后它替换X和Z。

This is how almost all compiler optimizations work. The code says "X". The compiler determines that if "Y" is true, then it can replace code "X" with code "Z" and there will be no detectable difference. It determines "Y" is true, and then it replaces "X" with "Z".

例如:

void func()
{
  int j = 2;
  foo();
  if (j == 2) bar();
   else baz();
}

编译器可以优化这富();酒吧(); 。编译器可以看到不能合法修改Ĵ的价值。如果富()不知何故神奇地计算出其中Ĵ是在栈上,并修改它,然后优化将改变在code的行为,但是这是程序员的使用魔术。

The compiler can optimize this to foo(); bar();. The compiler can see that foo cannot legally modify the value of j. If foo() somehow magically figures out where j is on the stack and modifies it, then the optimization will change the behavior of the code, but that's the programmer's fault for using "magic".

void func()
{
  int j = 2;
  foo(&j);
  if (j == 2) bar();
   else baz();
}

现在不能因为可以依法修改Ĵ的值没有任何魔法。 (假设编译器不能往里,在某些情况下就可以了。)

Now it can't because foo can legally modify the value of j without any magic. (Assuming the compiler can't look inside foo, which in some cases it can.)

如果你做的神奇,那么编译器可以使你突破code优化。遵守规则,不要使用魔法。

If you do "magic", then the compiler can make optimizations that break your code. Stick to the rules and don't use magic.

在您连接到例如,code依赖于编译器困扰把一个特定的值在被从未访问,并立即停止存在一个变量。编译器不需要做任何事情,对你的code的操作没有影响。

In the example you linked to, the code relies on the compiler bothering to put a particular value in a variable that is never accessed and immediately ceases to exist. The compiler is not required to do anything that has no effect on the operation of your code.

这可能影响了code的唯一方法是,如果它偷看栈的未分配部分或它们previously有其堆栈值依赖于新的分配。要求编译器执行,将产生巨大的优化数量不可能的,包括寄存器代替局部变量。

The only way that could effect the code is if it peeked at unallocated portions of the stack or relied on new allocations on the stack having values they previously had. Requiring the compiler to do that would make a huge number of optimizations impossible, including replacing local variables with registers.