简体   繁体   English

istreams的此三元操作安全吗?

[英]Is this ternary operation with istreams safe?

decltype(std::cin)&& is = (argc < 2 ? std::move(std::cin) : std::ifstream(argv[1]));

Is this dangerous? 这很危险吗? Is there a simpler/less dangerous way? 有没有更简单/不太危险的方法?

It works fine. 工作正常。 Example: 例:

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

I can't speak to exactly how safe your version is. 我无法确切地说出您的版本有多安全。 However, personally, I wouldn't want to move std::cin or bind to an std::ifstream unless I knew it was open(able). 但是,就我个人而言,除非我知道它是可打开的,否则我不希望移动 std::cin或将其绑定到std::ifstream I favour opening the std::ifstream first (if it has been specified in the argv ) and then binding to a std::istream& if is_open() else bind to std::cin . 我更喜欢先打开std::ifstream (如果已在argv指定),然后绑定到std::istream&如果is_open()绑定到std::cin

I do this all the time and it is perfectly safe: 我一直这样做,这是绝对安全的:

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;

    // ...
}

The answers to this SO question may also be of interest. 这个SO问题的答案也可能很有趣。

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

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