Hello,
In trying to port some Java code to C++ I'm disliking the std::stream's lack of copy constructors. I know exactly what the problem is, but I don't know what I can do about it. I have a dangling reference to a stream as a member variable of a class. My full code is very large but hopefully this will work to explain my dilema: (comments in caps indicate the problem areas, lowercase is extra information)
class PushbackReader{//class allows unread operations and limits read/unread to single char
protected:
istream & myreader;//SHOULD THIS BE A POINTER?
//other stuff for pushback buffer
public:
PushbackReader(string filename){myreader=ifstream(filename)/*rest*/}//CTOR MAKES FILE
PushbackReader(istream & reader) : myreader(reader){/*rest*/}//HOW TO PASS OTHER
//other things
int get(){
if(false/*check buffer*/) return -1;//return buffered char
else {
int c = myreader.get();
if(myreader.good()) return c;
else return -1;
}
}
};
class Tokenizer{//uses reader
protected:
shared_ptr<PushbackReader> reader;
public:
Tokenizer(string totokenize){
reader=shared_ptr<PushbackReader>(new PushbackReader(istringstream(totokenize)));
//THIS IS MY PROBLEM THE REFERENCE THE READER HAS TO THE STREAM
//ENDS UP A DANGLING POINTER BECAUSE IT GOES OUT OF SCOPE
//SHOULD I MAKE IT A FULL POINTER? OR IS THERE A BETTER WAY?
}
string /*really Token class*/ nextToken(){
char c = reader->get();//THIS CALL IS ACCESS VIOLATION
//use c somehow
return string(c,1);
}
};
int main(){
string s="string string string string";
Tokenizer tokenizer(s);
cout<<tokenizer.nextToken();
}
My problem is that the reference that the PushbackReader has goes out of scope after the constructor call, so I want to know that the best way to accomplish this goal is. Thanks in advance.