例如:

#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


尽管除了亲身经历外,我没有发现任何东西可以证明这一点,或者,如果您不想转到新行(并且绝对要刷新),则可以在第2行之后使用fflush(stdout)

10-07 18:57
查看更多