Coming from C, this example in Chapter 5 of Accelerated C++ caught my attention:
vector<Student_info> extract_fails(vector<Student_info>& students) {
vector<Student_info> pass, fail;
for (vector<Student_info>::size_type i = 0; i != students.size(); ++i)
if (fgrade(students[i]))
fail.push_back(students[i]);
else
pass.push_back(students[i]);
students = pass;
return fail;
}
Since fail is returned, I know it’s not a problem for it to be a local variable. But why is pass able to make it out of the local scope?
You probably believe that the reference
studentsis being “re-referenced” to the local variablepass. This is not the case. Instead,operator=is being called on the existing object passed in throughstudents, and the data frompassis copied to it.As you’re coming from C, you’re probably more familiar with pointers than with references. Let’s assume that
studentswas declared as a pointer, i.e.Your question implies that you believe the code you quoted is equivalent to the following
when in fact it is equivalent to this
The first of these two operations cannot, in fact, be carried out on a reference — references cannot be “re-referenced”.