为什么 g++使我的代码以与编写的顺序不同的顺序执行,如何禁用此“优化”?
例如:
#include <stdio.h>
#include <string>
int main() {
std::string* stuff(NULL);
printf("allocating memory..."); //line 2
stuff = new std::string[500000000]; //line 3
delete [] stuff; //line 4
return 0;
}
执行时在第 2 行之前运行第 3 行(也可能是第 4 行)。现在我知道这可能是一些很好的优化功能,但有时需要正确的顺序。
For example:
#include <stdio.h>
#include <string>
int main() {
std::string* stuff(NULL);
printf("allocating memory..."); //line 2
stuff = new std::string[500000000]; //line 3
delete [] stuff; //line 4
return 0;
}
when executed runs line 3 (and possibly line 4) before line 2. Now I know this is probably some good optimization feature but sometimes the right order is needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题就在这里:
在许多架构中,您都有缓冲输出,这意味着您在屏幕上打印的内容不会立即显示,而是存储在内存缓冲区中。要刷新缓冲区并确保立即打印它,您可以使用
尽管除了个人经验之外我没有找到任何东西可以证明这一点,或者,如果您不想换行(并且绝对确定刷新),您可以在第 2 行之后使用 fflush(stdout) 。
The problem is here:
In many architectures you have buffered output, which means that what you print on the screen is not shown immediately but stored in a memory buffer. To flush the buffer and ensure that he is printed immediately, you can use
although I didn't find anything to prove this besides personal experience, or alternatively, if you don't want to go to a new line (and be absolutely sure of flushing) you can use
fflush(stdout)
right after line 2.在 C++ 中,你可能想这样写:
In C++, you might want to write it like this:
-O0 标志禁用 GCC 中的所有优化。
但您观察到的效果很可能不是由于优化所致,而是文件 IO 缓冲的结果。
在 printf(...) 之后插入 fflush(stdout) 将使 IO 系统刷新缓冲区,在记录到文件的情况下应该为您提供正确的事件顺序(假设您正在记录对同一文件的 malloc() 调用,并且这是您观察到乱序事件的地方)。
-O0 flag disables all optimizations in GCC.
But the effect you are observing is most probably not due to an optimization but rather a result of file IO buffering.
Inserting fflush(stdout) just after printf(...) will make IO system flush the buffer which in case of logging to a file should give you the right order of events (assuming you are logging malloc() calls to the same file and this is where you observe out of order events).