The Evolving Search for Effective C++
Scott Meyers
Image © Florian Wizorek. Used with permission.
Last Revised: 12/5/14
1995
1991 1991 1997
Information Information Information Information Information Information Information Information
Effective Effective Books
1. Keep Items short.
2. Put Item titles in the imperative.
3. Make Item advice as specific as possible 4. Word Item titles carefully.
5. Prefer guidelines that say what to do over what not to do.
6. Tell the truth and nothing but the truth, but not necessarily the whole truth.
7. Back Items with solid technical arguments.
8. End each Item with a summary of its advice.
9. Know how to modulate the stridency of Item titles.
10. Cross reference liberally.
11. Minimize use of footnotes.
12. Be consistent when referring to yourself and your readers.
13. Seek out ruthless pre-publication reviewers.
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 5
Case Study
Item 42
Candidate Guideline
Prefer emplacement to insertion.
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 7
Emplacement vs. Insertion for Container<T>
Insertion functionstake parameters of type (reference to) T:
push_front(T)
push_back(T)
insert(position, T)
insert_after(position, T)Emplacement functionstake constructor arguments for T:
emplace_front(ctor args for T)
emplace_back(ctor args for T)
emplace(position, ctor args for T)
emplace_hint(position, ctor args for T)
emplace_after(position, ctor args for T)In std::vector<std::string>:
void push_back(const std::string&);
void push_back(std::string&&);
template<class... Args>
void emplace_back(Args&&...);
The Case for Emplacement
Avoids temporary creation:
std::vector<std::string> vs;
vs.push_back("xyzzy"); // create temp
// move temp into vector // destroy temp
vs.emplace_back("xyzzy"); // create string inside vector
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 9
The Case for Emplacement
For copyable/movable types, emplacement can do it all!
std::string queenOfDisco("Donna Summer");
vs.push_back(queenOfDisco); // copy-construct queenOfDisco // at end of vs
vs.emplace_back(queenOfDisco); // ditto
Ergo: Prefer emplacement to insertion.
Should never be slower, should sometimes be faster.
Right?Reality Check
Howard Hinnant’s experiments adding a T object to front of 3-element std::vector<T>.
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 11
Two cases:Reallocation unnecessary(capacity > size).
Reallocation required(capacity == size).
For each case:Add lvalue.
Add xvalue(e.g., std::move(existing object)).
Add prvalue(e.g., T(ctor args)).
Three std::vector implementations:
libc++(LLVM)
libstdc++(Gnu)
VS2013(Microsoft)Results (Functions Executed per insert/emplace)
Reallocation Unnecessary
Lvalue Xvalue Prvalue
I E I I - - I - -
Reallocation Required
- - I - - - -
libc++ libstdc++ VS2013 libc++ libstdc++ VS2013 libc++ libstdc++ VS2013
Observations
Much variation per scenario or implementation:
Number of functions executed.
Whether insertion or emplacement executes fewer functions.
Whether emplacement equivalent to insertion.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 13
Insight
Construction fundamentally different from assignment:
Construction can take arbitrary types.
Assignment generally takes same-type argument.class Widget { public:
Widget(int x, double d, std::string s); // arbitrary types Widget& operator=(const Widget&); // signatures per Widget& operator=(Widget&&); // convention };
Seeming exceptions may not really be exceptional:
template<typename charT> // simplified version class basic_string {
public:
basic_string& operator=(const charT* s); // specified as
... // *this = basic_string(s) };
Insight
Assignment for T generally requires argument of type T.
Typically negates emplacement’s performance advantage!So
emplace_back may beat push_back,
ditto for emplace_front,
but no reason to expect emplace to normally beat insert.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 15
construction construction assignment
Conclusions So Far
Emplacement into a Container<T> a potential win only when:
Object added to container via construction, not assignment.For std::vector/std::deque, true only for push_back/push_front.
Multiple arguments passed.Avoids need to create temporary to satisfy insertion interface.
Single argument passed not of type T.No reason to expect emplacing a T to beat inserting a T.
CWUK Containers
CWUK = “Containers with Unique Keys”
std::set<K>,std::unordered_set<K>
have nodes holding K objects.
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 17
std::map<K, V>,std::unordered_map<K, V>
have nodes holding std::pair<const K, V> objects.
K K K
K K
K K
K K
K
(K,V) (K,V)
(K,V)
(K,V)
(K,V) (K,V)
(K,V)
(K,V) (K,V) (K,V)
CWUK Container Declarations
template <class Key, class Compare = less<Key>, class Allocator = allocator<Key> >
class set;
template <class Key,
class Hash = hash<Key>,
class Pred = std::equal_to<Key>, class Alloc = std::allocator<Key> >
class unordered_set;
template <class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key, T> > >
class map;
template <class Key, class T,
class Hash = hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, T> > >
class unordered_map;
From C++14 Standard
CWUK Containers
Default “same value” comparisons are homogeneous:
std::less<K> compares two K objects.
std::equal_to<K> compares two K objects.Emplacement must create a K for comparison, even if value to be added is a duplicate.
If a duplicate, created K must then be destroyed.No reason to expect emplacement to run faster than insertion:
A temp object likely created to satisfy comparison function interface.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 19
CWUK Container Lookup Behavior
Insertion:
1. Compare parameter key to keys in container.
2. If parameter key isn’t in container, a. Dynamically allocate new node.
b. Copy or move parameter key into new node.
c. Link new node into container.
For duplicate keys:
No node allocation/deallocation.
No copying or moving parameter key.Emplacement:
1. Dynamically allocate memory for new node.
2. Construct key in new node.
3. Compare new node key to keys in container.
4. If new node key isn’t in container, a. link new node into container.
else
b. Destroy new node.
For duplicate keys:
Node allocated and deallocated.
Key in new node constructed + destructed.Additional Conclusion
Emplacement into a Container<T> a likely lose (vis-a-vis insertion) when:
Container rejects duplicate keys and duplicate keys aren’t uncommon.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 21
The Conversion Consideration
Consider:
std::vector<std::regex> regexes;
regexes.push_back(nullptr); // error! nullptr isn't a std::regex // and there's no implicit conversion regexes.emplace_back(nullptr); // compiles!
Huh?
The Constructor in Question
template <class charT,
class traits = regex_traits<charT> >
class basic_regex { ...
explicit basic_regex(const charT* p,
flag_type f = regex_constants::ECMAScript);
...
};
Requires: p shall not be a null pointer.
Hence:
regexes.emplace_back(nullptr); // UB! (Precondition violation) But why does emplace_back compile when push_back doesn’t?
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 23
From C++14 Standard
Direct vs. Copy Initialization
Direct initialization may call explicit constructors.
Copy initialization can’t.How know which used where?
Memorize :-(std::regex r1(nullptr); // compiles! Direct initialization // may call explicit ctor
std::regex r2{nullptr}; // ditto
std::regex r3 = nullptr; // error! Copy initialization // can't call explicit ctor
§ 8.5/15-16
Direct vs. Copy Initialization
Emplacement functions use direct initialization:
regexes.emplace_back(nullptr); // compiles!
Insertion functions use copy initialization:
regexes.push_back(nullptr); // error!
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 25
One More Conclusion
Emplacement less “safe” than insertion.
May invoke explicit constructors.Summary
Performance:
Emplacement can reduce number of constructions/destructions.
In theory, emplacement never costs more than insertion.
In practice, emplacement often does.
Emplacement most likely a win when:Value being added is constructed into the container, not assigned.
Argument(s) passed are different from T (for Container<T>).
Value to be added unlikely to be rejected as a duplicate.
Safety:
Insertion “respects” explicit constructors, emplacement doesn’t.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 27
Guideline
Many thanks to:
Stephan T. Lavavej
Howard Hinnant
Michael WinterbergPrefer emplacement to insertion.
Intermission
Promulgation Promulgation Promulgation Promulgation Promulgation Promulgation Promulgation Promulgation
Promulgating the Message
1991:
Writing
PresentationsScott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 31
2014:
Writing
Presentations
VideoImage: “Loudspeakers,” Pelle Sten @ flickr
The Writing Landscape: 1991
Black ink on white, fixed-size pages.
The Writing Landscape: 2014
Flashback to my TOC 2009 talk:
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 33
Scott Meyers, Software Development Consultant http://www.aristeia.com/
Copyrighted material, all rights reserved.
Slide 3
The Vision and Why Authors Matter
Printed book
Computer screen
Portable electronic book reader
Multipurpose portable device
Audio device Manuscript
from author What's in here…
…affects how easy and effective these transitions are
The Goal
Platform-agnostic manuscript from author.
Facilitates:
Exploitation of platforms' strengths and capabilities.
Accommodationof their weaknesses.Scott Meyers, Software Development Consultant http://www.aristeia.com/
Copyrighted material, all rights reserved.
Slide 5
Some Platform Variations
Color? Display Size
Diagrams, Graphs,
Tables?
Page- Based?
Dynamic? Personal- izable?
Rarely Medium Yes Yes No
Maybe with POD
Typically Big Yes Maybe Yes In
concept
Maybe Medium Maybe Maybe Yes In
concept
Typically Small Yes, but
small Maybe Yes In
concept
Maybe Typically
small Maybe No Rarely In
concept
What Works Poorly
Authors design/write books that are:
Static
Monochrome
Page-based
VisibleOther formats suffer.
Conventional manuscript from author
Scott Meyers, Software Development Consultant http://www.aristeia.com/
Copyrighted material, all rights reserved.
Slide 7
What may go in a Platform-Agnostic Manuscript?
Anything that “works” in printed form.
The usual suspects:
Text, diagrams, tables, photographs, etc.In addition:
Color
Video/Animations
AudioChallenge: Adopting New Tools
New expository tools:
Color, video/animations, audio Authors need to learn:
What works where? Why?
What doesn’t? Why not?As true for novelists as for technical writers.
Regarding Color...
Legitimate uses (IMO):
Code highlighting.
Syntax coloring.
Diagrams and tables.
Visual appeal.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 34
Not Everybody Gets It
The Line Length Problem
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 36
64
The Solution?
The Animation Approach
E.g., in Sean Parent’s “C++ Seasoning” at GoingNative 2013:
The Animation Approach
E.g., in Sean Parent’s “C++ Seasoning” at GoingNative 2013:
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 44
The Animation Approach
E.g., in Sean Parent’s “C++ Seasoning” at GoingNative 2013:
The Animation Approach
E.g., in Sean Parent’s “C++ Seasoning” at GoingNative 2013:
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 46
The Animation Approach
Advantages:
Good for live, remote, and asynchronous audiences.Disadvantages:
Lots of up-front work. Lots.
Inflexible.The Solution?
Touch-based laser pointer and annotation support?
“Paul Wagner on using iPad/Doceri in the Classroom”
Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 48
Base guidelines on thorough analysis and solid technical arguments.
Base guidelines on thorough analysis and solid technical arguments.
Design live presentations to be recorded.
Design live presentations to be recorded.
Write for modern digital devices.
Take-Aways
Further Information
“Automatic Detection of Programming Errors: Initial Thoughts on a lint++,”Scott Meyers and Moises Lejter, Proceedings of the 1991 USENIX C++ Conference, April 1991.
“Effective Effective Books,”Scott Meyers, The View From Aristeia, 23 January 2013.
“insert vs. emplace,”Howard Hinnant, 28 July 2014, http://tinyurl.com/lxf67ky.
Effective Modern C++, Scott Meyers, O’Reilly, 2015.
“Authoring Challenges in a Multiplatform World,”Scott Meyers, Tools of Change, February 2009.
“The Line-Length Problem,”Scott Meyers, The View from Aristeia, 13 March 2013.
“clang-format: Automatic formatting for C++,”Daniel Jasper, 2013 European LLVM Conference, 29 April 2013.
“C++ Seasoning,”Sean Parent, GoingNative 2013, 4 September 2013.
“Paul Wagner on using iPad/Doceri in the Classroom,”YouTube, 22 November 2011.Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 50
Use discount code AUTHD at oreilly.com
for 40%-50% off!
Licensing Information
Scott Meyers licenses materials for this and other training courses for commercial or personal use. Details:
Commercial use: http://aristeia.com/Licensing/licensing.html
Personal use: http://aristeia.com/Licensing/personalUse.html Courses currently available for personal use include:Scott Meyers, Software Development Consultant http://www.aristeia.com/
© 2014 Scott Meyers, all rights reserved.
Slide 52
About Scott Meyers
Scott Meyers is one of the world’s foremost authorities on C++. His web site,
http://aristeia.com/
provides information on: