Skip to Content
C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
book

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

by Herb Sutter, Andrei Alexandrescu
October 2004
Intermediate to advanced
240 pages
6h 22m
English
Addison-Wesley Professional
Content preview from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

48. Prefer initialization to assignment in constructors

Summary

Set once, use everywhere: In constructors, using initialization instead of assignment to set member variables prevents needless run-time work and takes the same amount of typing.

Discussion

Constructors generate initialization code under the covers. Consider:

image

In reality, constructor’s code is generated as if you wrote:

A() : s1_(), s2_() { s1_ = "Hello, "; s2_ = "world"; }

That is, the objects not explicitly initialized by you are automatically initialized using their default constructors, and then assigned to using their assignment operators. Most often, the assignment operator ...

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

C++ Core Guidelines Explained: Best Practices for Modern C++

C++ Core Guidelines Explained: Best Practices for Modern C++

Rainer Grimm
C++ Templates: The Complete Guide, 2nd Edition

C++ Templates: The Complete Guide, 2nd Edition

David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor

Publisher Resources

ISBN: 0321113586Purchase book