例如:
#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 行)。现在我知道这可能是一些很好的优化功能,但有时需要正确的顺序。
最佳答案
问题出在这里:
printf("allocating memory..."); //line 2
在许多架构中,您都有缓冲输出,这意味着您在屏幕上打印的内容不会立即显示,而是存储在内存缓冲区中。要刷新缓冲区并确保立即打印他,您可以使用
printf("allocating memory...\n"); //line 2 with the \n character that flushes the buffer
尽管除了个人经验之外我没有找到任何东西来证明这一点,或者如果你不想换行(并且绝对确定要刷新)你可以使用 fflush(stdout)
在第 2 行之后。
关于c++ - 为什么 g++ 使我的代码以不同于写入的顺序执行,我如何禁用此 "optimization"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8952079/