【问题标题】:Is this ternary operation with istreams safe?istreams 的这种三元运算安全吗?
【发布时间】:2015-12-01 06:24:02
【问题描述】:
decltype(std::cin)&& is = (argc < 2 ? std::move(std::cin) : std::ifstream(argv[1]));

这很危险吗?有没有更简单/不那么危险的方法?

它工作正常。示例:

int i = 42;
is >> i; // enter 50
std::cout << i; // 50

【问题讨论】:

  • 这样说吧:如果你不得不花时间思考做这样的事情是否安全,你可能无论如何都不应该这样做。

标签: c++ c++11 istream


【解决方案1】:

我无法确切说明您的版本有多安全。但是,就个人而言,我不想移动 std::cin 或绑定到std::ifstream,除非我知道它是开放的(能够)。我倾向于先打开std::ifstream(如果它已在argv 中指定),然后如果is_open() 绑定到std::istream&amp;,否则绑定到std::cin

我一直这样做这个,而且非常安全:

int main(int argc, char* argv[])
{
    std::ifstream ifs;

    if(argc > 1)
    {
        ifs.open(argv[1]);
        // check error and maybe exit
    }

    std::istream& is = ifs.is_open() ? ifs : std::cin;

    // ...
}

this SO question 的答案可能也很有趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 2011-11-09
    • 2022-01-17
    • 2011-06-19
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多