Chapter 8. Tweaks

For every general technique or feature in C++, there are circumstances where it’s reasonable to use it, and there are circumstances where it’s not. Describing when it makes sense to use a general technique or feature is usually fairly straightforward, but this chapter covers two exceptions. The general technique is pass by value, and the general feature is emplacement. The decision about when to employ them is affected by so many factors, the best advice I can offer is to consider their use. Nevertheless, both are important players in effective modern C++ programming, and the Items that follow provide the information you’ll need to determine whether using them is appropriate for your software.

Item 41: Consider pass by value for copyable parameters that are cheap to move and always copied.

Some function parameters are intended to be copied.1 For example, a member function addName might copy its parameter into a private container. For efficiency, such a function should copy lvalue arguments, but move rvalue arguments:

class Widget {
  void addName(const std::string& newName)    // take lvalue;
  { names.push_back(newName); }               // copy it

  void addName(std::string&& newName)         // take rvalue;
  { names.push_back(std::move(newName)); }    // move it; see// Item 25 for use
                                              // of std::move
  std::vector<std::string> names;

This works, but it requires writing two functions that do essentially the same thing. That chafes a bit: two functions to declare, two functions ...

Get Effective Modern C++ now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.