1

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.

moth
  • 345
  • 1
  • 13

1 Answers1

7

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;
}
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • Yes but I've used const. – moth Apr 28 '14 at 15:27
  • @FarorTahal, doesn't matter. – Shoe Apr 28 '14 at 15:28
  • 2
    The object is gone after you exit the function. Doesn't matter that you hold a const reference to a dead object. – FKaria Apr 28 '14 at 15:28
  • Thank you FKaria, I've understood. @Jeffrey Thus, Jeffrey, with RVO we don't care to return variable by ref or not? – moth Apr 28 '14 at 15:30
  • 3
    @FarorTahal If you returned by value, binding to a `const` reference would extend the returned object's lifetime. But you don't return by value. – juanchopanza Apr 28 '14 at 15:32
  • @juanchopanza Yet I return by value: "return vint". But I think I've understood, to return by const ref, before I have to bind the returned value to a const ref, or the returned variable have to be a preexisting variable like an object's attribut for instance. Isn't it? – moth Apr 28 '14 at 15:41
  • @FarorTahal This: `const vector& getVInt()` means you return a reference, not by value. – juanchopanza Apr 28 '14 at 15:42
  • 1
    @FarorTahal, just return by value and make a copy. That's the easiest and most efficient ways. What juanchopanza refers to, is the fact that temporary binded to reference (both `const` and non-`const`) will extend the lifetime of the object. In this specific case it doesn't change much and I think it's much cleaner by value. – Shoe Apr 28 '14 at 15:44
  • Even if `RVO` doesn't apply, it will be moved thanks to move-semantics in C++11. – masoud Apr 28 '14 at 15:45
  • @Jefffrey and @M M Ok, thank you. So with RVO or move-semantics in C++11, it doesn't change much for memory to return by value or ref? – moth Apr 28 '14 at 15:49
  • @TahalFaror, it's no time with RVO and constant complexity with move-semantics for `std::vector`. So, yeah, you should definitely don't worry about performance here. – Shoe Apr 28 '14 at 15:53
  • So in which case I should use return of const ref or non-const ref? – moth Apr 28 '14 at 15:58