0 c++ g++ compiler-optimization
例如:
#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;
}
Run Code Online (Sandbox Code Playgroud)
执行时在第2行之前运行第3行(可能还有第4行).现在我知道这可能是一些很好的优化功能,但有时需要正确的顺序.
Pie*_*ice 10
问题出在这里:
printf("allocating memory..."); //line 2
Run Code Online (Sandbox Code Playgroud)
在许多体系结构中,您都有缓冲输出,这意味着您在屏幕上打印的内容不会立即显示,而是存储在内存缓冲区中.要冲洗缓冲区并确保立即打印,您可以使用
printf("allocating memory...\n"); //line 2 with the \n character that flushes the buffer
Run Code Online (Sandbox Code Playgroud)
虽然除了个人经验之外我没有找到任何证明这一点的东西,或者,如果你不想去新线(并且绝对确定冲洗),你可以fflush(stdout)在第2行之后使用.