为什么g ++使我的代码以不同于写入的顺序执行,如何禁用这种"优化"?

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行之后使用.

  • 该行为继承自C(C99的7.19.3).流可以是_unbuffered_,_line buffered_或_fully buffered_.标准错误未完全缓冲,如果确定标准错误未连接到交互式设备,则标准输出仅允许完全缓冲.这允许stdout为_line buffered_或_unbuffered_,并且在大多数'unices'上通常_line buffered_意味着换行字符将刷新它. (5认同)
  • 我不认为`\n`保证刷新(不像c ++ std :: endl). (3认同)