繁体   English   中英

为什么这段代码时不时会产生不同的output?

[英]Why does this code produce different output from time to time?

编译器:

➜ ~ /usr/bin/c++ --version
Apple clang version 11.0.0 (clang-1100.0.33.8)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

代码:

#include <iostream>

#include <exception>
#include <cstdlib>


void f() {
    try {
        throw std::runtime_error("Exception message.");
    } catch(std::runtime_error& e) {
        std::cout << e.what() << std::endl;
        throw;
    }
}


int main() {
    using namespace std;
    try {
        f();
    } catch(std::exception& e) {
        cout << e.what() << endl;
        terminate();
    }
    return EXIT_SUCCESS;
}

我发现如果我摆脱了捕获中的“terminate()”,它会起作用,但我不知道为什么会这样?

随机产生三个输出:

libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Exception message.
Exception message.
Exception message.


Exception message.
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Exception message.
Exception message.


Exception message.
Exception message.
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Exception message.

PS对不起,也许问题不正确,我是初学者。

对于初学者,您的常规cout打印会发送到stdout ,但“终止于...”消息会发送到stderr 您观察到的原因是您的终端(或 IDE)正在读取这两个 output 通道并将它们呈现在一个位置。 根据您的终端/IDE 用于合并这两个流的算法, stderr消息可能会出现在您注意到的地方。

如果您将流指向相同的文件描述符,则您的操作系统将负责合并。 按如下方式运行您的程序:

./my_program 2>&1

现在您的终端将按顺序显示消息,而不会意外重新排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM