Question

Here is my function:

const vector<int>& getVInt(){
  vector<int> vint;
  (...)
  return vint;
}

And,

  vector<int> x = getVInt();

returns:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check

and

const vector<int>& x = getVInt();

returns nothing (a vector with a size different from 0 but with no value when I use x.at(i) ).

I looked for in forum but answers about temprorary and const ref doesn't help me to understand that.

Thank you.

Was it helpful?

Solution

You are returning a reference to a local object. That's undefined behavior. Return by copy instead, the copy will be elided thanks to RVO (return value optimization).

std::vector<int> getVInt(){
    std::vector<int> vint;
    // …
    return vint;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top