Sunday, April 26, 2015

New EMC++ Excerpt Now Online

We've just put a new excerpt from Effective Modern C++ online. This time it's
  • Item 41: Consider pass by value for copyable parameters that are cheap to move and always copied.
It's available at the same place as all the other Items we've put up, namely here.

This Item grew out of my concern that move semantics is causing pass by value to lose its traditional reputation of being unreasonably expensive for user-defined types. More and more, I see coding examples from "thought leaders" (i.e., people who write articles or books or who give presentations at conferences, etc. -- you know, people like me :-}) where common types (e.g., std::vector, std::string, std::unique_ptr) are passed by value with nary a second thought. This worries me. I think it's a bad habit to get into. I blogged about why I think this is a particularly unjustifiable practice for move-only types like std::unique_ptr  here, and the ensuing comment stream makes for interesting reading, IMO.

What I really object to isn't the practice itself, but the risk that people will employ it without being aware of its consequences. I also worry about people taking an idea that can be reasonable under fairly constrained circumstances and overly generalizing it. In my view, pass by value is a strategy that should typically be considered only if (1) you have a parameter whose type is copyable (i.e., isn't a move-only type), (2) its move operations are cheap, and (3) the parameter will be unconditionally copied. Even then, I argue that you should only consider the use of pass by value, because even if all three criteria are fulfilled, there are still situations where it can incur a significant performance penalty.

I hope you find this latest excerpt from the book interesting and useful. I also hope you enjoy my finding a way to work allusions to both Mary Poppins and Jabberwocky into a single Item. I haven't checked, but I'd like to think I'm the only author who's found a reason to use supercalifragilisticexpialidocious in a book on C++.

Scott

2 comments:

  1. Hello Scott,

    Considering that I’ve not used C++ in almost 10 years, I may as well be about to commit an absolute faux pas, however, I believe that in the second point, you probably wanted to write “copy operations are cheap," instead of the current “its move operations are cheap.” Having decided to act on this desire to share the thought, I can now only hope that I have, in the process, not made an absolute fool of myself.

    Take care.

    ReplyDelete
  2. @Irfan: It's correct as written. Check out the Item to see why. (Briefly, it's because using pass by value costs you an extra move.)

    ReplyDelete