Skip to Content
Effective Modern C++
book

Effective Modern C++

by Scott Meyers
November 2014
Intermediate to advanced
336 pages
9h 37m
English
O'Reilly Media, Inc.
Content preview from Effective Modern C++

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 {
public:
  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
private:
  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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Effective C++, Third Edition

Effective C++, Third Edition

Scott Meyers
Embracing Modern C++ Safely

Embracing Modern C++ Safely

John Lakos, Vittorio Romeo, Rostislav Khlebnikov, Alisdair Meredith
C++ Software Design

C++ Software Design

Klaus Iglberger

Publisher Resources

ISBN: 9781491908419Errata Page