Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library
All
Stack Overflow 64
This Year
Stack Overflow 1
This Month
Stack Overflow 9
The answer is not trivial. If you have 2 main sections in your software: 1st setup, 2nd lookup and lookup is used more than setup: the sorted
vector
could be faster, because of 2 reasons:lower_bound
<algorithm>
function is faster than the usual tree implementation of<set>
,std::vector
memory is allocated less heap page, so there will be less page faults while you are looking for an element.If the usage is mixed, or lookup is not more then setup, than
<set>
will be faster. More info: Scott Meyers: Effective STL, Item 23.Here is an example of using a functor to perform two accumulations in parallel.
[Note that you could also consider using
std::accumulate()
, with an appropriate overload foroperator+
.]As for virtual functors, you cannot do these directly, as STL functions take functors by value, not by reference (so you'd get a slicing problem). You'd need to implement a sort of "proxy" functor that in turn contains a reference to your virtual functor.* Along the lines of:
* Scott Meyers gives a good example of this technique in Item 38 of his excellent Effective STL.
There is a companion book to the Effective C++ series, which is called "Effective STL". It's a good starting point for learning about best practises using the Standard C++ library (neé STL).
Scott Meyers describes this technique very well in Effective C++.
The meaning of that quote should be taken at face value. For the majority of the STL algorithms, you should not implement your predicate functor such that it has observable state (AKA "side effects"), because:
The simplest way to enforce this upon yourself is to define
operator()
asconst
.There are exceptions, such as
for_each
, for which none of the above apply. You are free to use stateful functors here. For more info, see this excellent article: http://drdobbs.com/cpp/184403769.Behind the scenes, the authors of your STL implementation are free to write the
remove_if
(and other algorithms) any way they like, so long as it conforms to the requirements laid down by the standard. There's no real reason to worry too much about exactly why you're getting the behaviour you're seeing, beyond acknowledging that it's undefined. If you want to know the specifics, I would just take a look at the code forremove_if
in the STL implementation that you're using.As for your side-note; this is not "corruption", it's simply an artifact of how
remove_if
works (this would occur even for a valid predicate). The only requirement is that all the elements to the left ofpos
are valid (because they are to be retained). There are no requirements on what elements exist frompos
onward (see here). (Chapter 32 of "Effective STL" by Scott Meyers has a good explanation of whyremove_if
(and so on) behave like this).TL;DR
Extra parentheses change the meaning of a C++ program in the following contexts:
decltype
expressionsPreventing argument-dependent name lookup
As is detailed in Annex A of the Standard, a
post-fix expression
of the form(expression)
is aprimary expression
, but not anid-expression
, and therefore not anunqualified-id
. This means that argument-dependent name lookup is prevented in function calls of the form(fun)(arg)
compared to the conventional formfun(arg)
.3.4.2 Argument-dependent name lookup [basic.lookup.argdep]
Enabling the comma operator in list contexts
The comma operator has a special meaning in most list-like contexts (function and template arguments, initializer lists etc.). Parentheses of the form
a, (b, c), d
in such contexts can enable the comma operator compared to the regular forma, b, c, d
where the comma operator does not apply.5.18 Comma operator [expr.comma]
Ambiguity resolution of vexing parses
Backward compatibility with C and its arcane function declaration syntax can lead to surprising parsing ambiguities, known as vexing parses. Essentially, anything that can be parsed as a declaration will be parsed as one, even though a competing parse would also apply.
6.8 Ambiguity resolution [stmt.ambig]
8.2 Ambiguity resolution [dcl.ambig.res]
A famous example of this is the Most Vexing Parse, a name popularized by Scott Meyers in Item 6 of his Effective STL book:
This declares a function,
data
, whose return type islist<int>
. The function data takes two parameters:dataFile
. It's type isistream_iterator<int>
. The parentheses arounddataFile
are superfluous and are ignored.istream_iterator<int>
.Placing extra parentheses around the first function argument (parentheses around the second argument are illegal) will resolve the ambiguity
C++11 has brace-initializer syntax that allows to side-step such parsing problems in many contexts.
Deducing referenceness in
decltype
expressionsIn contrast to
auto
type deduction,decltype
allows referenceness (lvalue and rvalue references) to be deduced. The rules distinguish betweendecltype(e)
anddecltype((e))
expressions:7.1.6.2 Simple type specifiers [dcl.type.simple]
The rules for
decltype(auto)
have a similar meaning for extra parentheses in the RHS of the initializing expression. Here's an example from the C++FAQ and this related Q&AThe first returns
string
, the second returnsstring &
, which is a reference to the local variablestr
.Preventing preprocessor macro related errors
There is a host of subtleties with preprocessor macros in their interaction with the C++ language proper, the most common of which are listed below
#define TIMES(A, B) (A) * (B);
in order to avoid unwanted operator precedence (e.g. inTIMES(1 + 2, 2 + 1)
which yields 9 but would yield 6 without the parentheses around(A)
and(B)
assert((std::is_same<int, int>::value));
which would otherwise not compile(min)(a, b)
(with the unwanted side effect of also disabling ADL)I think you'd better have some lectures about good practices and why they are good. That should help you more than a code analysis tool (in the beginning at least).
I suggest you read the series of Effective C++ and **Effective STL books, at least. See alsot The Definitive C++ Book Guide and List
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 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
Note that 'no match' is signaled wuth the end iterator:
Note, that
-O3 -march=native
for g++)Edit since you have shown more code, I now realize you actually want to detect (sub)string length. You could use
Of course, that assumes you'd want to convert the char[] to std::string for the purpose. In practice, that might be a perfectly valid idea, because of SSO (Small String Optimization) found in nearly all implementations of the C++ standard library. (see Items 13-16 in Herb Sutter's More Exceptional C++, or Scott Meyers' discussion of commercial std::string implementations in Effective STL).
I was in the same situation 12 years ago when I got my first programming job out of college. I didn't do any open source but I managed to gain a lot of practical and advanced C++ knowledge by reading books (the dead tree kind).
In particular, there was an excellent series by Scott Meyers which I feel helped the most in turning me from newbie to professional:
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
More Effective C++: 35 New Ways to Improve Your Programs and Designs
Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library
The topics in these books range from beginner to advanced. It took me about 2 years working in C++ to understand every chapter in these books, so don't be disheartened if it goes over your head at some point... just try reading it again later :)
The reason for the error is that you are calling the copy constructor of auto_ptr my_player in fooPlayerFactory::MakePlayerO() which is a const method. That means that is cannot modify its members.
However the copy constructor of auto_ptr DOES modify the right hand side so returning my_player trys to change its pointer to 0 (NULL), while assigning the original pointer to the auto_ptr in the return value.
The signature of the copy constuctor is
not
The copy constructor of auto_ptr assigns ownership of the pointer to the left hand side, the right hand side then holds nothing.
I don't think you want to use auto_ptr here, you probably want boost::smart_ptr
It looks like you have mixed up two uses for auto_ptr
The first is as poor man's boost::scoped_ptr. This is to manage a single instance of a pointer in a class, the class manages the life time of the pointer. In this case you don't normally return this pointer outside your class (you can it is legal, but boost::smart_ptr / boost::weak_ptr would be better so clients can participate the life time of the pointer)
The second is its main purpose which is to return a newly created pointer to the caller of a function in an exception safe way.
eg
As I said I think you have mixed these two uses auto_ptr is a subtle beast you should read the auto_ptr docs carefully. It is also covered very well in Effective STL by Scott Meyers.