I'm having compiler errors associated with this block of text. I've added comments pertaining to the errors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class PwdReader //interface for reading the passwd file
{
...
PwdReader(istream& i) //error: no appropriate default constructor for istream available
{
in = i; //error: operator= cannot access private member in class istream
}
virtual ~PwdReader()
{
}
private:
istream in;
};
If for a moment we ignore std::istream as a whole, and focus on what you're doing, then maybe you'll get the point. In any class, all non-POD data members are usually best initialized in the class member initialization list i.e.
Did you see where I initialized the data member f? Doing Foo( std::string const & f_ ) { f = f_; } is called assignment, not initialization. Now you may ask What ( the f**k ) is the difference between the two? See here -> http://www.parashift.com/c++-faq/init-lists.html
IIRC, in C++, all subclasses of -- and including -- std::ios_base are not copyable, it means neither the class member initialization is allowed nor through assignment via the overloaded operator=. You have two options, however:
1) Make is a reference, allow your ctor take a std::istream & , let is reference the std::istream object.
2) Make your own std::istream using rdbuf
Below is 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
class PwdReader
{
std::istream &is;
public:
PwdReader( std::istream &s ): is( s ) {}
};
int main()
{
PwdReader ref_reader{ std::cin };
return 0;
}
@JLBorges I'm aware of movable stream but what I didn't know is that the GNU library implementation is broken, I guess I should have used Clang when I was trying to compile the moving ctor.
On Linux, by default clang++ links with the GNU library; to link with LLVM libc++, specify -stdlib=libc++
(On BSDs, it links with libc++ by default; on Windows, clang++ links with the Microsoft library, which is fine.)
I've changed my code to PwdReader(istream& i): in(move(i)) {} and it's giving almost the same error, with the exception of now saying the method's trying to access a protected member.