1
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
  • 3
    Let's put it this way: if you have to spend time thinking about whether doing something like this is safe, you probably shouldn't do it regardless. – T.C. Sep 05 '15 at 03:36

1 Answers1

1

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). 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.

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.

Galik
  • 47,303
  • 4
  • 80
  • 117