Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot assign or copy iostream object?

iostream and other stream class are not actually class, but typedefs, right?

Here is the problem, I tried to initialize a istream object in initialization list, but unfortunately I got an error, code goes bellow:

class A 
{
    public:
        A(istream &is=cin): ais(is)
        {}

    private:
        istream ais;
};

Can't compile with g++, error:

synthesized method ‘std::basic_istream<char, std::char_traits<char> >::basic_istream(const std::basic_istream<char, std::char_traits<char> >&)’ first required here 

I searched SO, found that, iostream cannot be assigned or copy. But why cannot I initialize it in the initialization list?

Cuz I think, the initialization list will invoke the object's constructor/copy-constructor, right?

like image 246
Alcott Avatar asked Jun 23 '26 21:06

Alcott


1 Answers

Your code attempts to turn one istream, the one passed to the constructor, into two istreams, the one that was passed to the constructor and ais. An istream object represents that actual stream itself. There is only one stream and there is no way to somehow turn it into two streams.

It's not even clear what that would mean. If there's some data on the stream, does whichever stream reads first get it? Or do they both get it? If so, who or what duplicates it?

An istream is like a file itself. You cannot turn one file into two files without copying the data from one to the other yourself. You can, however, have as many references or pointers to the same istream as you want. The solution to your problem is probably to make ais a reference.

like image 150
David Schwartz Avatar answered Jun 25 '26 10:06

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!