Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition)
All
Hacker News 7
This Year
Stack Overflow 3
This Month
Stack Overflow 2
Ok so you are learning C++ then learn the good practices from the start and avoid C++ pitfalls. Declaring and using C++ global objects that way can lead to very nasty behavior and long debugging sessions because you can't be sure the global object background which is declared at file global scope is initialized and properly constructed when you use it in another file. When you use such an object ,let's call it B, in another global object A in another file you cannot be sure B is initialized before the A and that leads to very nasty bugs or if you are lucky a crash. The solution then: make you object background a local static object i.e. local to a function like so:
That's it. Anywhere you want to use background just call getBackground(). The first time you call it, background local static will be initialized and good to use.
Some will say that this technique is related to the singleton design pattern but this is not my intent here it is just the proper way to use global objects if you absolutely need to. C++ is a great language especially with the release of C++11 but it has some pitfalls you need need to be aware of. Do yourself a favor: grab a copy of Effetive C++ it will teach almost everything you need to know to use the language properly
The Konrad reply is OK, just a puntualization about the arrays.... There is a way to create an array of items(not pointers) and here it follows:
This approach is described here: http://www.amazon.com/gp/product/0321334876?ie=UTF8&tag=aristeia.com-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321334876
Jonathan already resumed the differences between
using namespace foo;
andusing foo::Bar;
but I think his answer is unfortunately incomplete.First:
using namespace
should never appear in a header file. By doing so you might render it impossible to use in combination with other header files because of a symbol clash...Second: in general, you should try to limit the scope of the symbols as much as possible, you probably already do it while writing code:
Here it would be useless (and polluting) to have
myString
declared outside thefor
loop. In fact, that very advice can be found in a number of books:From Scott Meyers' Effective C++, Item 26: Postpone variable definitions as long as possible.
From Herb Sutter and Andrei Alexandrescu's C++ Coding Standard, Item 18: Declare variables as locally as possible
There is no reason not to do the same with
using
declarations.Third: consider alternatives to
using
: namespace aliasing andtypedef
.What are the advantages ?
using
and allow easy change of underlying type too.I had the same doubt as you until I came across this book by the C++ Guru Scott Meyers. Refer the third Item in this book where he talks in details about using
const
.Just follow this advice
const
appears to the left of the asterisk, what's pointed to is constantconst
appears to the right of the asterisk, the pointer itself is constantconst
appears on both sides, both are constantYou should declare variables/instances of object as locally as possible. So, in this case, B would be the best option.
Consider that if you declare it at the top of your function body other people reading your code might wonder where you actually use the object. Therefore, by having the declaration close to where you actually use it will makes it easier to read.
There should not be any huge performance difference between case A and B.
There are some special cases such as allocating big chunks of memory or a thread pool for example. In these cases, since it might be time and ressources consumming you might need to find a better place to allocate them.
If you new to programming, you might want to consider reading Scott Meyers book, Effective C++. Item 26 talks about it : Postpone variable definitions as long as possible.
I took a class under Bjarne Stroustrup and he highly recommended Tour of C++ [0] as the best way to learn modern C++ for someone who already has some programming experience. That and of course, Effective C++[1] by Scott Meyers.
[0] - https://www.amazon.com/Tour-C-Depth/dp/0321958314
[1] - https://www.amazon.com/Effective-Specific-Improve-Programs-D...
But I actually think we (software devs) need to focus more on mastering languages as opposed to learning many languages at a surface level.
Books like "Effective C++" (https://www.amazon.ca/Effective-Specific-Improve-Programs-De...) really showed me the huge divide between knowing a language and mastering a language.
1. Programming pearls, http://www.amazon.com/Programming-Pearls-2nd-Jon-Bentley/dp/...
2. Effective C++, http://www.amazon.com/Effective-Specific-Improve-Programs-De...
3. Programming Problems, http://www.amazon.com/Programming-Problems-Primer-Technical-...
The reason for these texts is not because they are overtly insightful or well written, it is because they have a large number of problems with completely coded solutions. After working through these basics, programming interviews are much more enjoyable.
[1] http://www.amazon.com/Effective-Specific-Improve-Programs-De... (Make sure you get the latest edition, a lot has changed for the better)
Problem Summary
There are two competing concerns in this question.
Subsystem
s, allowing their removal at the right time.Subsystem
s need to know that theSubsystem
they are using is valid.Handling #1
System
owns theSubsystem
s and should manage their life-cycle with it's own scope. Usingshared_ptr
s for this is particularly useful as it simplifies destruction, but you should not be handing them out because then you loose the determinism you are seeking with regard to their deallocation.Handling #2
This is the more intersting concern to address. Describing the problem in more detail, you need clients to receive an object which behaves like a
Subsystem
while thatSubsystem
(and it's parentSystem
) exists, but behaves appropriately after aSubsystem
is destroyed.This is easily solved by a combination of the Proxy Pattern, the State Pattern and the Null Object Pattern. While this may seem to be a bit complex of a solution, 'There is a simplicity only to be had on the other side of complexity.' As Library/API developers, we must go the extra mile to make our systems robust. Further, we want our systems to behave intuitively as a user expects, and to decay gracefully when they attempt to misuse them. There are many solutions to this problem, however, this one should get you to that all important point where, as you and Scott Meyers say, it is "easy to use correctly and hard to use incorrectly.'
Now, I am assuming that in reality,
System
deals in some base class ofSubsystem
s, from which you derive various differentSubsystem
s. I've introduced it below asSubsystemBase
. You need to introduce a Proxy object,SubsystemProxy
below, which implements the interface ofSubsystemBase
by forwarding requests to the object it is proxying. (In this sense, it is very much like a special purpose application of the Decorator Pattern.) EachSubsystem
creates one of these objects, which it holds via ashared_ptr
, and returns when requested viaGetProxy()
, which is called by the parentSystem
object whenGetSubsystem()
is called.When a
System
goes out of scope, each of it'sSubsystem
objects gets destructed. In their destructor, they callmProxy->Nullify()
, which causes their Proxy objects to change their State. They do this by changing to point to a Null Object, which implements theSubsystemBase
interface, but does so by doing nothing.Using the State Pattern here has allowed the client application to be completely oblivious to whether or not a particular
Subsystem
exists. Moreover, it does not need to check pointers or keep around instances that should have been destroyed.The Proxy Pattern allows the client to be dependent on a light weight object that completely wraps up the details of the API's inner workings, and maintains a constant, uniform interface.
The Null Object Pattern allows the Proxy to function after the original
Subsystem
has been removed.Sample Code
I had placed a rough pseudo-code quality example here, but I wasn't satisfied with it. I've rewritten it to be a precise, compiling (I used g++) example of what I have described above. To get it to work, I had to introduce a few other classes, but their uses should be clear from their names. I employed the Singleton Pattern for the
NullSubsystem
class, as it makes sense that you wouldn't need more than one.ProxyableSubsystemBase
completely abstracts the Proxying behavior away from theSubsystem
, allowing it to be ignorant of this behavior. Here is the UML Diagram of the classes:Example Code:
Output from the code:
Other Thoughts:
An interesting article I read in one of the Game Programming Gems books talks about using Null Objects for debugging and development. They were specifically talking about using Null Graphics Models and Textures, such as a checkerboard texture to make missing models really stand out. The same could be applied here by changing out the
NullSubsystem
for aReportingSubsystem
which would log the call and possibly the callstack whenever it is accessed. This would allow you or your library's clients to track down where they are depending on something that has gone out of scope, but without the need to cause a crash.I mentioned in a comment @Arkadiy that the circular dependency he brought up between

System
andSubsystem
is a bit unpleasant. It can easily be remedied by havingSystem
derive from an interface on whichSubsystem
depends, an application of Robert C Martin's Dependency Inversion Principle. Better still would be to isolate the functionality thatSubsystem
s need from their parent, write an interface for that, then hold onto an implementor of that interface inSystem
and pass it to theSubsystem
s, which would hold it via ashared_ptr
. For example, you might haveLoggerInterface
, which yourSubsystem
uses to write to the log, then you could deriveCoutLogger
orFileLogger
from it, and keep an instance of such inSystem
.Beginner
Introductory, no previous programming experience
Introductory, with previous programming experience
C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]
A Tour of C++ (Bjarne Stroustrup) (EBOOK) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.
Accelerated C++ (Andrew Koenig and Barbara Moo) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction into the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach at teaching the language.) [Review]
Thinking in C++ (Bruce Eckel) Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they’re marred by a number of trivial errors (e.g. maintaining that temporaries are automatically
const
), with no official errata list. A partial 3rd party errata list is available at (http://www.computersciencelab.com/Eckel.htm), but it’s apparently not maintained.* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.
Best practices
Effective C++ (Scott Meyers) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]
Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.
Intermediate
More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.
Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]
More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object oriented programming in C++ and correct use of the STL. [Review]
Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using nonmember functions and the single responsibility principle. [Review]
C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]
C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition is scheduled for 2017. [Review]
Advanced
Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multimethods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]
C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)
C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications.
Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by typetraits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.
Reference Style - All Levels
The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much alike it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review]
C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]
The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]
C++11/14 References:
The C++ Standard (INCITS/ISO/IEC 14882-2011) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. As usual, the first release was quite expensive ($300+ US), but it has now been released in electronic form for $60US.
The C++14 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++17.
Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++1y/C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.
The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.
The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.
cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.
Classics / Older
Note: Some information contained within these books may not be up-to-date or no longer considered best practice.
The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.
Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]
Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.
Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly a good read, if it only was up to date. It was written long before C++98, and misses on many features (e.g. namespaces) important for large scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is expected in 2015.
Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.
The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.
The thing to keep in mind here is templates are different from language features like generics in languages like C#.
It is a fairly safe simplification to think of templates as an advanced preprocessor that is type aware. This is the idea behind Template metaprogramming (TMP) which is basically compile time programming.
Much like the preprocessor templates are expanded and the result goes through all of the same optimization stages as your normal logic.
Here is an example of rewritting your logic in a style more consistent with TMP. This uses function specialization.
TMP was actually discovered as a happy accident and is pretty much the bread and butter of the STL and Boost.
It is turing complete so you can do all sorts of computation at compile time.
It is lazily evaluated so you could implement your own compile time asserts by putting invalid logic in a specialization of a template that you don't want to be used. For example if I were to comment out the
foo<false>
specialization and tried to use it likefoo<false>(1.0);
the compiler would complain, although it would be perfectly happy withfoo<true>(1.0);
.Here is another Stack Overflow post that demonstrates this.
Further reading if interested:
I think this statement reflects the confusion here (emphasis mine):
In idiomatic C++, there are two uses for deriving from a class:
boost::iterator_facade
-- which show up when the CRTP is in use.There is absolutely no reason to publicly derive a class in C++ if you're not trying to do something polymorphic. The language comes with free functions as a standard feature of the language, and free functions are what you should be using here.
Think of it this way -- do you really want to force clients of your code to convert to using some proprietary string class simply because you want to tack on a few methods? Because unlike in Java or C# (or most similar object oriented languages), when you derive a class in C++ most users of the base class need to know about that kind of a change. In Java/C#, classes are usually accessed through references, which are similar to C++'s pointers. Therefore, there's a level of indirection involved which decouples the clients of your class, allowing you to substitute a derived class without other clients knowing.
However, in C++, classes are value types -- unlike in most other OO languages. The easiest way to see this is what's known as the slicing problem. Basically, consider:
If you pass your own string to this method, the copy constructor for
std::string
will be called to make a copy, not the copy constructor for your derived object -- no matter what child class ofstd::string
is passed. This can lead to inconsistency between your methods and anything attached to the string. The functionStringToNumber
cannot simply take whatever your derived object is and copy that, simply because your derived object probably has a different size than astd::string
-- but this function was compiled to reserve only the space for astd::string
in automatic storage. In Java and C# this is not a problem because the only thing like automatic storage involved are reference types, and the references are always the same size. Not so in C++.Long story short -- don't use inheritance to tack on methods in C++. That's not idiomatic and results in problems with the language. Use non-friend, non-member functions where possible, followed by composition. Don't use inheritance unless you're template metaprogramming or want polymorphic behavior. For more information, see Scott Meyers' Effective C++ Item 23: Prefer non-member non-friend functions to member functions.
EDIT: Here's a more complete example showing the slicing problem. You can see it's output on codepad.org
After a brief look at SeqAn manual I came up with the following example:
The point is that the design that SeqAn is telling is moving from the realm of usual OOP programming (with polymorphism, type abstractions and etc.) to C++ template programming (more precisely see Item 1 in Effective C++). The same like there are zellions of books on OOP design, not less, if not more, there are material on Template C++ programming (see The Definitive C++ Book Guide and List for both kinds of programming techniques and more).
In this example, I show two techniques of designing that the SeqAn documentation emphasizes.
There is a base implementing some kind of operation that has several steps common for other subclasses. The base provide kind of Template Method (there is nothing related to C++ templates there, it is purely OOP pattern, just the name has the same word) from operations - setting an interface (not OOP interface, but C++ Template interface) for the deriving classes. Those subclasses, in their turn, implement those operations. You get static (resolved at compile time behaviour) polymorphism (type that has an interface that has different behavior from one instance to another). There is no runtime polymorphism because for runtime (OOP realm) those all are different types, they are all different for compile time as well. This polymorphism exists in C++ templates (templates parameters and templates declarations). Example: Boost Iterator Facade.
Tag dispatching technique employs function overloading resolution depending on the argument(s) type(s). It helps when you have free function as part of your API and chose necessary one to call depending on situation (example STL Iterators
iterator_tag
(s) and iterator free functions). For exmaple, consider OOP Visitor Pattern and you haveAbstractVisitor
andKnockingVisitor
. You take a vector ofBase*
and callaccept
on each, that callsvisit
and yourKnockingVisitor
does the knocking. With tag dispatching you use tags. This might be a lame comparation between OOP techniques and tag dispatching, but it is just one of many possible examples. Like with OOP design where and what pattern to use, with C++ Templates techniques you need experience.This example is quite primitive, because there is no actual task behind it is design, however, when you have an ambitious goal that gets more interesting and complicated. C++ Templates might be one of the choices to archive it.
You should take a look at the book "Effective C++", especially Chapter 2. http://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876
Chapter 2: Constructors, Destructors, and Assignment Operators
For those that use Effective C++ as a C++ programming reference, this issue is covered in Item 33 (Avoid hiding inherited names.) in the book.
The guide to the language by Stroustrup:
Scott Meyers's triple are quite useful: Effective C++, More Effective C++, and Effective STL.
Also see these questions:
- https://stackoverflow.com/questions/155762/best-c-resource
- Java FAQ equivalent of C++ FAQ lite?
- C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
- What C++ pitfalls should I avoid?
- New to C++. Question about constant pointers