5

I've seen many statements that when you want to copy a value inside a function it is better to pass it by value and do an std::move inside that function (since C++11). See here and here for example.

If that is correct, then why does the std containers in C++11 such as std::vector still have pass-by-ref overloads for methods such as push_back?

Wouldn't it be better to just change them to pass-by-value methods and call std::move inside them?

JFMR
  • 23,265
  • 4
  • 52
  • 76
amfcosta
  • 1,049
  • 10
  • 21
  • Why break backward compatibility? If you pass an lvalue the `const T&` version is called and if you pass a rvalue then the `T&&` version is called. – NathanOliver Feb 12 '16 at 19:48
  • I'm not sure if the duplicate is the right one. Let me know if not. But if you had only a value overload, you'd be forced to make an extra copy when passing lvalues. Remember moving is not always efficient. – juanchopanza Feb 12 '16 at 19:54
  • @juanchopanza: it would only make a single copy that it would then move into the vector's memory. Having an lvalue reference version (just) saves the move and extra destruction of the moved-from temporary, which might be optimized away completely, or might be significant (eg, for a large POD type) – Chris Dodd Feb 12 '16 at 20:28
  • @ChrisDodd The point is that the move could be expensive. Why incur it if you don't need to? Threre are better ways to do this, as can be seen in the duplicate. – juanchopanza Feb 12 '16 at 20:30
  • 4
    This question wasn't a duplicate, but I've now addressed the answer to this question in http://stackoverflow.com/a/28130619/576911 in order to make this a duplicate. – Howard Hinnant Feb 12 '16 at 20:31
  • 2
    Whatever your position: **Always** pass by recipe X is *always* bad advice. One has to keep brain in gear when programming, and don't trust anyone claiming that they have the one true way that is always better than those other ways. – Howard Hinnant Feb 12 '16 at 20:48
  • Some objects are not movable – M.M Feb 12 '16 at 23:11
  • @howard-hinnant You did right to address this in the other question. I know that the "always pass by X" is bad, I just wanted to know why it was bad in this case. Thanks. – amfcosta Feb 13 '16 at 00:37

0 Answers0