Accelerated c++ istream&

In this program there is the following function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
istream& read_hw(istream& in, vector<double>& hw) 
{
    if(in)
    {
        hw.clear();

        double x;
        while(in >> x)
            hw.push_back(x);

            in.clear();
    }
    return in;
}

I'm mainly confused about the istream& read_hw() and then the parameter istream& in.
What exactly is going on?
What does istream& mean?
What does istream& read_hw() mean?
If you know the book you'll know what I mean in context or if not then this function reads input into a vector...
std::istream is a class type that other input stream types is derived from. You only have to write the function once for std::istream and it will automatically work for the derived types like std::ifstream, std::istringstream and for the std::cin object.

& in this context means that it is a reference. The function takes references a reference to a std::istream and a reference to a std::vector<double> as argument and returns a reference to a std::istream.

That it returns a reference to the stream object allows you to use it loops and ifs like operator>> and std::getline. In the code above you have while(in >> x). This works because operator>> returns a reference to the in object. This actually tests if the in object is in a good state so you know if the last read from it was successful or not.
Please note that in this example it is ok to return a reference because the variable is actually a reference to something outside of the function.
But you can't return a reference to a variable created in the function this way, because when it would be used after the function has been executed, the variable designed by the reference would already have been destroyed at the end of the function
Topic archived. No new replies allowed.