简体   繁体   中英

Moving std::istream

I have a Scanner class to tokenize streams of characters coming from files, cin , etc.

class Scanner {
public:
  Scanner(std::istream&& c) : input{std::move(c)} {}

private:
  std::istream input;
};

This code does not compile because the move constructor of std::istream is protected. I could use a reference to the stream instead, but then, I have no guarantee that someone is not playing with my stream outside of the Scanner class ( ss below).

  std::string code = "this is code";
  std::stringstream ss{code};
  Scanner scanner{ss};

Is there a neat way to address this issue, or do people just use std::istream& and hope for the best?

From what I can remember about my work with stream objects.

You need to think about this a bit differently.

class Scanner {
public:
  Scanner() {}
  virtual void scan(std::istream & p_stream);
};

Your Scanner class could just be focused on scanning the input for whatever, not actually containing it.

Now it can be focused purely on a single task.

Then you need to work out what is the best way for you to keep the stream object alive. I suggest a separate class for that task.

I would have written this as a comment, but there's too much here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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