0

I am reading about moving constructors and assignments in Stroustrup's c++ textbook. Below is a motivating example given by the author. The return statement in the code illustrates copying a large vector can be inefficient.

Vector operator+(const Vector& a, const Vector& b) {

  if (a.size()!=b.size()) throw Vector_size_mismatch{};

  Vector res(a.size()); 
  for (int i=0; i!=a.size(); ++i) res[i]=a[i]+b[i]; 
  return res;
}

Question: Wouldn't it be simpler to change the return type to reference Vector& to avoid the efficiency issues of copying?

zell
  • 9,830
  • 10
  • 62
  • 115
  • What exactly does the book says about this example? The code looks good to me as it is. Your compiler shouldn't copy or move `res` at all because of NRVO (and even if it fails to NRVO, it has to move `res` instead of copying it). – HolyBlackCat Jul 13 '19 at 11:58
  • 5
    Returning a reference to `res` will create a dangling reference as `res` will be destroyed before it is used. – Richard Critten Jul 13 '19 at 11:58
  • @RichardCritten Thanks. Why will `res` be destroyed before being used? – zell Jul 13 '19 at 12:44
  • 1
    `res` is a local variable of `operator+` and is destroyed before the function returns to the caller. Any use of the result returned from `operator+` happens after it returns. So if `operator+` returns a reference (to `res`), this reference will refer to the already destroyed `res`. – Richard Critten Jul 13 '19 at 13:12
  • @RichardCritten Another thought: Would one be able to implement "move" with a pointer, Vector*, so to avoid the dangling reference issue you mentioned? – zell Jul 13 '19 at 13:35
  • Read the duplicate, modern compilers make these sort of (pre-)optimisations irrelevant. – Richard Critten Jul 13 '19 at 13:58

0 Answers0