I am learning c++ and trying some things. The compiler is not throwing an error at comment 2 line.
int main(){
vector<double> a1;
a1.push_back(3);
a1.push_back(7);
a1.push_back(2);
vector<double>& a2 = a1; //COMMENT 1: This line has no error
vector<double>& a4 = print(a2); //COMMENT 2: Why this line has error? R value is an object then it should be referenced by a4?
return 0;
}
vector<double> print(vector<double>& a3){
cout<<"In print function the size of vector is :";
cout<<a3.size()<<endl;
return a3;
}
Blehh, so... yes, the return value is a temporary. And as such, it doesn't make sense to hold a reference to it (just imagine: a reference that refers to nothing when the temporary is destroyed). Thus, it's disallowed.
You can fix this in several ways:
I. Hold a const reference to it, as in
const vector<double> &retVal = print();
const references extend the lifetime of the bound temporary to the lifetime of the reference.
II. Simply return it by value:
vector<double> retVal = print();
III. Return a reference to an object that you know will have sufficient lifetime, e. g. a class member:
class Foo {
vector<double> vec;
public:
vector<double> &print() {
return vec;
}
};
Foo f;
vector<double> &retVal = f.print();
DO NOT, however, return a reference to a temporary from the function like this:
// this is wrong:
vector<double> &print()
{
vector<double> v;
return v;
}
because it invokes undefined behavior. (Note that this is different from your example, because you return the argument of the function which is of course alive, but it's worth noting this case as it's a common mistake to make.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With