Merge pull request #219 from tkruse/mdast-idempot

Achieve mdast idempotency (4-space markdown indent, single empty lines)
This commit is contained in:
Gabriel Dos Reis
2015-10-02 03:37:36 -07:00

View File

@@ -87,7 +87,6 @@ Definitions of terms used to express and discuss the rules, that are not languag
* resource
* exception guarantee
# <a name="S-abstract"></a> Abstract
This document is a set of guidelines for using C++ well.
@@ -127,7 +126,6 @@ We plan to build tools for that and hope others will too.
Comments and suggestions for improvements are most welcome.
We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
# <a name="S-introduction"></a> In: Introduction
This is a set of core guidelines for modern C++, C++14, and taking likely future enhancements and taking ISO Technical Specifications (TSs) into account.
@@ -142,12 +140,10 @@ Introduction summary:
* [In.struct: The structure of this document](#SS-struct)
* [In.sec: Major sections](#SS-sec)
## <a name="SS-readers"></a> In.target: Target readership
All C++ programmers. This includes [programmers who might consider C](#S-cpl).
## <a name="SS-aims"></a> In.aims: Aims
The purpose of this document is to help developers to adopt modern C++ (C++11, C++14, and soon C++17) and to achieve a more uniform style across code bases.
@@ -229,7 +225,6 @@ The rules are not value-neutral.
They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance.
They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance.
## <a name="SS-force"></a> In.force: Enforcement
Rules with no enforcement are unmanageable for large code bases.
@@ -260,7 +255,6 @@ For a start, we have a few profiles corresponding to common needs (desires, idea
The profiles are intended to be used by tools, but also serve as an aid to the human reader.
We do not limit our comment in the **Enforcement** sections to things we know how to enforce; some comments are mere wishes that might inspire some tool builder.
## <a name="SS-struct"></a> In.struct: The structure of this document
Each rule (guideline, suggestion) can have several parts:
@@ -291,7 +285,6 @@ This is not a language manual.
It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
Recommended information sources can be found in [the references](#S-references).
## <a name="SS-sec"></a> In.sec: Major sections
* [P: Philosophy](#S-philosophy)
@@ -327,7 +320,6 @@ These sections are not orthogonal.
Each section (e.g., "P" for "Philosophy") and each subsection (e.g., "C.hier" for "Class Hierarchies (OOP)") have an abbreviation for ease of searching and reference.
The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").
# <a name="S-philosophy"></a> P: Philosophy
The rules in this section are very general.
@@ -667,8 +659,8 @@ How do we transfer both ownership and all information needed for validating use?
##### Example
* ???
* show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
* ???
* show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
Or strings as "free-style" options
##### Enforcement
@@ -1339,7 +1331,6 @@ This is a major source of errors.
template <class F, class ...Args>
explicit thread(F&& f, Args&&... args); // good: throw system_error if unable to start the new thread
##### Note: What is an error?
An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
@@ -1436,7 +1427,6 @@ Every object passed as a raw pointer (or iterator) is assumed to be owned by the
* (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
* (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
### <a name="Ri-nullptr"></a> I.12: Declare a pointer that must not be null as `not_null`
##### Reason
@@ -1706,12 +1696,10 @@ Other function rules:
Functions have strong similarities to lambdas and function objects so see also Section ???.
## <a name="SS-fct-def"></a> F.def: Function definitions
A function definition is a function declaration that also specifies the function's implementation, the function body.
### <a name="Rf-package"></a> F.1: "Package" meaningful operations as carefully named functions
##### Reason
@@ -1764,7 +1752,6 @@ Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unl
* See [Keep functions short](#Rf-single)
* Flag identical and very similar lambdas used in different places.
### <a name="Rf-logical"></a> F.2: A function should perform a single logical operation
##### Reason
@@ -1839,6 +1826,7 @@ Consider
double simpleFunc(double val, int flag1, int flag2)
// simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags.
{
double intermediate;
if (flag1 > 0) {
intermediate = func1(val);
@@ -1881,6 +1869,7 @@ We can refactor:
double simpleFunc(double val, int flag1, int flag2)
// simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags.
{
if (flag1 > 0)
return func1_muon(val, flag2);
if (flag1 == -1)
@@ -2211,7 +2200,6 @@ A `not_null<T*>` is assumed not to be the `nullptr`; a `T*` may be the `nullptr`
* (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
### <a name="Rf-nullptr"></a> F.17: Use a `not_null<T>` to indicate that "null" is not a valid value
##### Reason
@@ -2803,6 +2791,7 @@ Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
* Warn on use of a named non-generic lambda (e.g., `auto x = [](int i){ /*...*/; };`) that captures nothing and appears at global scope. Write an ordinary function instead.
### <a name="Rf-default-args"></a> F.51: Prefer overloading over default arguments for virtual functions
??? possibly other situations?
##### Reason
@@ -3070,7 +3059,6 @@ Concrete type rule summary:
* [C.10: Prefer a concrete type over more complicated classes](#Rc-concrete)
* [C.11: Make concrete types regular](#Rc-regular)
### <a name="Rc-concrete"></a> C.10 Prefer a concrete type over more complicated classes
##### Reason
@@ -3225,13 +3213,11 @@ Other default operations rules:
* [C.88: Make `<` symmetric with respect of operand types and `noexcept`](#Rc-lt)
* [C.89: Make a `hash` `noexcept`](#Rc-hash)
## <a name="SS-defop"></a> C.defop: Default Operations
By default, the language supply the default operations with their default semantics.
However, a programmer can disable or replace these defaults.
### <a name="Rc-zero"></a> C.20: If you can avoid defining default operations, do
##### Reason
@@ -3543,8 +3529,7 @@ The default copy operation will just copy the `p1.p` into `p2.p` leading to a do
auto p2 = p1; // error: double deletion
}
##### Note
##### Note
Often the simplest way to get a destructor is to replace the pointer with a smart pointer (e.g., `std::unique_ptr`)
and let the compiler arrange for proper destruction to be done implicitly.
@@ -3930,7 +3915,6 @@ However, most realistic `Date` classes has a "first date" (e.g. January 1, 1970
* Flag classes without a default constructor
### <a name="Rc-default00"></a> C.44: Prefer default constructors to be simple and non-throwing
##### Reason
@@ -4337,6 +4321,7 @@ But what if you can get significant better performance by not making a temporary
T* elem;
int sz;
};
}
Vector& Vector::operator=(const Vector& a)
@@ -4513,6 +4498,7 @@ Consider:
##### Enforcement
Equivalent to what is done for [copy-assignment](#Rc-copy-assignment).
* (Simple) An assignment operator should not be virtual. Here be dragons!
* (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
* (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.
@@ -5145,7 +5131,7 @@ not using this (over)general interface in favor of a particular interface found
##### Enforcement
???
???
## C.hierclass: Designing classes in a hierarchy:
@@ -5425,7 +5411,7 @@ This a relatively rare use because implementation can often be organized into a
##### Reason
???
???
##### Example
@@ -5838,7 +5824,7 @@ Union rule summary:
##### Reason
???
???
##### Example
@@ -5936,7 +5922,7 @@ Enumeration rule summary:
##### Reason
???
???
##### Example
@@ -8571,7 +8557,6 @@ Some people optimize out of habit or because it's fun.
##### Note
If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless.
???
### <a name="Rper-simple"></a> PER.4: Don't assume that complicated code is necessarily faster than simple code
@@ -8627,32 +8612,26 @@ make the job of the optimizer much harder. Simple code often optimizes better th
???
### <a name="Rper-Comp"></a> PER.11: Move computation from run time to compile time
???
### <a name="Rper-alias"></a> PER.12: Eliminate redundant aliases
???
### <a name="Rper-indirect"></a> PER.13: Eliminate redundant indirections
???
### <a name="Rper-alloc"></a> PER.14: Minimize the number of allocations and deallocations
???
### <a name="Rper-alloc0"></a> PER.15: Do not allocate on a critical branch
???
### <a name="Rper-compact"></a> PER.16: Use compact data structures
##### Reason
@@ -9336,7 +9315,6 @@ Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii).
##### Note
??? mostly, you can afford exceptions and code gets simpler with exceptions ???
**See also**: [Discussion](#Sd-???).
# <a name="S-const"></a> Con: Constants and Immutability
@@ -9523,12 +9501,10 @@ Other template rules summary:
* [T.144: Don't specialize function templates](#Rt-specialize-function)
* [T.??: ????](#Rt-???)
## <a name="SS-GP"></a> T.gp: Generic programming
Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
### <a name="Rt-raise"></a> T.1: Use templates to raise the level of abstraction of code
##### Reason
@@ -10599,8 +10575,7 @@ In many cases you can provide a stable interface by not parameterizing a base; s
##### Enforcement
* Flag virtual functions that depend on a template argument. ??? False positives
### <a name="Rt-array"></a> T.81: Do not mix hierarchies and arrays
### <a name="Rt-array"></a> T.81: Do not mix hierarchies and arrays
##### Reason
@@ -11493,9 +11468,9 @@ It is more likely to be stable, well-maintained, and widely available than your
???
### SL.???: Use character-level input only when you have to; _expr.low_.
### SL.???: Use character-level input only when you have to; *expr.low*.
### SL.???: When reading, always consider ill-formed input; _expr.low_.
### SL.???: When reading, always consider ill-formed input; *expr.low*.
## SL.regex: Regex
@@ -11523,7 +11498,6 @@ This section contains ideas about ???
???
# <a name="S-not"></a> Non-Rules and myths
This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend.
@@ -11538,7 +11512,6 @@ Non-rule summary:
* two-phase initialization
* goto exit
# <a name="S-references"></a> RF: References
Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++.
@@ -11574,47 +11547,45 @@ Reference sections:
* [RS.video: Videos about "modern C++"](#SS-vid)
* [RF.man: Manuals](#SS-man)
## <a name="SS-rules"></a> RF.rules: Coding rules
* [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html).
???.
???.
* [Bloomberg: BDE C++ Coding](https://github.com/bloomberg/bde/wiki/CodingStandards.pdf).
Has a strong emphasis on code organization and layout.
Has a strong emphasis on code organization and layout.
* Facebook: ???
* [GCC Coding Conventions](https://gcc.gnu.org/codingconventions.html).
C++03 and (reasonably) a bit backwards looking.
C++03 and (reasonably) a bit backwards looking.
* [Google C++ Style Guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.html).
Too timid and reflects its 1990s origins.
[A critique from 2014](https://www.linkedin.com/pulse/20140503193653-3046051-why-google-style-guide-for-c-is-a-deal-breaker).
Google are busy updating their code base and we don't know how accurately the posted guideline reflects their actual code.
This set of recommendations is evolving.
Too timid and reflects its 1990s origins.
[A critique from 2014](https://www.linkedin.com/pulse/20140503193653-3046051-why-google-style-guide-for-c-is-a-deal-breaker).
Google are busy updating their code base and we don't know how accurately the posted guideline reflects their actual code.
This set of recommendations is evolving.
* [JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS](http://www.stroustrup.com/JSF-AV-rules.pdf).
Document Number 2RDU00001 Rev C. December 2005.
For flight control software.
For hard real time.
This means that it is necessarily very restrictive ("if the program fails somebody dies").
For example, no free store allocation or deallocation may occur after the plane takes off (no memory overflow and no fragmentation allowed).
No exception may be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
Libraries used have to have been approved for mission critical applications.
Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
Recommended, but note its very specific focus.
Document Number 2RDU00001 Rev C. December 2005.
For flight control software.
For hard real time.
This means that it is necessarily very restrictive ("if the program fails somebody dies").
For example, no free store allocation or deallocation may occur after the plane takes off (no memory overflow and no fragmentation allowed).
No exception may be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
Libraries used have to have been approved for mission critical applications.
Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
Recommended, but note its very specific focus.
* [Mozilla Portability Guide](https://developer.mozilla.org/en-US/docs/Mozilla/C%2B%2B_Portability_Guide).
As the name indicate, this aims for portability across many (old) compilers.
As such, it is restrictive.
As the name indicate, this aims for portability across many (old) compilers.
As such, it is restrictive.
* [Geosoft.no: C++ Programming Style Guidelines](http://geosoft.no/development/cppstyle.html).
???.
???.
* [Possibility.com: C++ Coding Standard](http://www.possibility.com/Cpp/CppCodingStandard.html).
???.
???.
* [SEI CERT: Secure C++ Coding Standard](https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637).
A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
Many of their rules apply generally.
A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
Many of their rules apply generally.
* [High Integrity C++ Coding Standard](http://www.codingstandard.com/).
* [llvm](http://llvm.org/docs/CodingStandards.html).
Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
* ???
## <a name="SS-books"></a> RF.books: Books with coding guidelines
* [Meyers14](#Meyers14) Scott Meyers: Effective Modern C++ (???). Addison-Wesley 2014. Beware of overly technical and overly definite rules.
@@ -11622,16 +11593,15 @@ Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
* [Stroustrup05](#Stroustrup05) Bjarne Stroustrup: [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
LCSD05. October 2005.
* [Stroustrup14](#Stroustrup05) Stroustrup: [A Tour of C++](http://www.stroustrup.com/Tour.html).
Addison Wesley 2014.
Each chapter ends with an advice section consisting of a set of recommendations.
Addison Wesley 2014.
Each chapter ends with an advice section consisting of a set of recommendations.
* [Stroustrup13](#Stroustrup13) Stroustrup: [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html).
Addison Wesley 2013.
Each chapter ends with an advice section consisting of a set of recommendations.
Addison Wesley 2013.
Each chapter ends with an advice section consisting of a set of recommendations.
* Stroustrup: [Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
Mostly low-level naming and layout rules.
Primarily a teaching tool.
for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
Mostly low-level naming and layout rules.
Primarily a teaching tool.
## <a name="SS-C++"></a> RF.C++: C++ Programming (C++11/C++14)
@@ -11639,7 +11609,6 @@ Primarily a teaching tool.
* Tour++
* Programming: Principles and Practice using C++
## <a name="SS-web"></a> RF.web: Websites
* [isocpp.org](http://www.isocpp.com)
@@ -11650,8 +11619,6 @@ Primarily a teaching tool.
* [Adobe open source](http://www.adobe.com/open-source.html)
* [Poco libraries](http://pocoproject.org/)
## <a name="SS-vid"></a> RS.video: Videos about "modern C++"
* Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012.
@@ -11661,7 +11628,6 @@ Primarily a teaching tool.
* Sutter: ???
* ??? more ???
## <a name="SS-man"></a> RF.man: Manuals
* ISO C++ Standard C++11
@@ -11670,7 +11636,6 @@ Primarily a teaching tool.
* ISO C++ Concepts TS
* WG21 Ranges report
## <a name="SS-ack"></a> Acknowledgements
Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.:
@@ -11683,7 +11648,6 @@ Thanks to the many people who contributed rules, suggestions, supporting informa
* Zhuang, Jiangang (Jeff)
* Sergey Zubkov
# <a name="S-profile"></a> Profiles
A "profile" is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee. "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be). "Portably enforceable" means they are like language rules, so programmers can count on enforcement tools giving the same answer for the same code.
@@ -12141,11 +12105,6 @@ If code is using an unmodified standard library, then there are still workaround
## <a name="SS-lifetime"></a> Lifetime safety profile
# <a name="S-gsl"></a> GSL: Guideline support library
The GSL is a small library of facilities designed to support this set of guidelines.
@@ -12158,7 +12117,6 @@ Where desirable, they can be "instrumented" with additional functionality (e.g.,
These Guidelines assume a `variant` type, but this is not currently in GSL because the design is being actively refined in the standards committee.
## <a name="SS-views"></a> GSL.view: Views
These types allow the user to distinguish between owning and non-owning pointers and between pointers to a single object and pointers to the first element of a sequence.
@@ -12217,7 +12175,6 @@ French accent optional.
Use `not_null<zstring>` for C-style strings that cannot be `nullptr`. ??? Do we need a name for `not_null<zstring>`? or is its ugliness a feature?
## <a name="SS-ownership"></a> GSL.owner: Ownership pointers
* `unique_ptr<T>` // unique ownership: `std::unique_ptr<T>`
@@ -12233,7 +12190,6 @@ Use `not_null<zstring>` for C-style strings that cannot be `nullptr`. ??? Do we
// ??? `Expect` in under control of some options (enforcement, error message, alternatives to terminate)
* `Ensures` // postcondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
## <a name="SS-utilities"></a> GSL.util: Utilities
* `finally` // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f`
@@ -12243,7 +12199,6 @@ Use `not_null<zstring>` for C-style strings that cannot be `nullptr`. ??? Do we
(I don't know how to do that except with a macro: `#define implicit`).
* `move_owner` // `p=move_owner(q)` means `p=q` but ???
## <a name="SS-concepts"></a> GSL.concept: Concepts
These concepts (type predicates) are borrowed from Andrew Sutton's Origin library, the Range proposal, and the ISO WG21 Palo Alto TR.
@@ -12272,7 +12227,6 @@ The notation is that of the ISO WG21 Concepts TS (???ref???).
* `Relation`
* ...
# <a name="S-naming"></a> NL: Naming and layout rules
Consistent naming and layout are helpful. If for no other reason because it minimizes "my style is better than your style" arguments.
@@ -12302,7 +12256,6 @@ IDEs also tend to have defaults and a range of alternatives.These rules are sugg
More specific and detailed rules are easier to enforce.
### <a name="Rl-comments"></a> NL.1: Don't say in comments what can be clearly stated in code
##### Reason
@@ -12398,7 +12351,6 @@ Some styles distinguishes types from non-types.
This is not evil.
### <a name="Rl-name-length"></a> NL.7: Make the length of a name roughly proportional to the length of its scope
**Rationale**: ???
@@ -12482,8 +12434,6 @@ This rule applies to non-macro symbolic constants
* Flag macros with lower-case letters
* Flag ALL_CAPS non-macro names
### <a name="Rl-camel"></a> NL.10: Avoid CamelCase
##### Reason
@@ -12531,8 +12481,6 @@ Some IDEs have their own opinions and adds distracting space.
We value well-placed whitespace as a significant help for readability. Just don't overdo it.
### <a name="Rl-order"></a> NL.16: Use a conventional class member declaration order
##### Reason
@@ -12651,113 +12599,88 @@ This section covers answers to frequently asked questions about these guidelines
See the top of this page. This is an open source project to maintain modern authoritative guidelines for writing C++ code using the current C++ Standard (as of this writing, C++14). The guidelines are designed to be modern, machine-enforceable wherever possible, and open to contributions and forking so that organizations can easily incorporate them into their own corporate coding guidelines.
### <a name="Faq-announced"></a> FAQ.2: When and where was this work first announced?
It was announced by [Bjarne Stroustrup in his CppCon 2015 opening keynote, “Writing Good C++14”](https://isocpp.org/blog/2015/09/stroustrup-cppcon15-keynote). See also the [accompanying isocpp.org blog post](https://isocpp.org/blog/2015/09/bjarne-stroustrup-announces-cpp-core-guidelines), and for the rationale of the type and memory safety guidelines see [Herb Sutters follow-up CppCon 2015 talk, “Writing Good C++14... By Default”](https://isocpp.org/blog/2015/09/sutter-cppcon15-day2plenary).
### <a name="Faq-maintainers"></a> FAQ.3: Who are the authors and maintainers of these guidelines?
The initial primary authors and maintainers are Bjarne Stroustrup and Herb Sutter, and the guidelines so far were developed with contributions from experts at CERN, Microsoft, Morgan Stanley, and several other organizations. At the time of their release, the guidelines are in a "0.6" state, and contributions are welcome. As Stroustrup said in his announcement: "We need help!"
### <a name="Faq-contribute"></a> FAQ.4: How can I contribute?
See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
### <a name="Faq-maintainer"></a> FAQ.5: How can I become an editor/maintainer?
By contributing a lot first and having the consistent quality of your contributions recognized. See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
### <a name="Faq-iso"></a> FAQ.6: Have these guidelines been approved by the ISO C++ standards committee? Do they represent the consensus of the committee?
No. These guidelines are outside the standard. They are intended to serve the standard, and be maintained as current guidelines about how to use the current Standard C++ effectively. We aim to keep them in sync with the standard as that is evolved by the committee.
### <a name="Faq-isocpp"></a> FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`?
Because `isocpp` is the Standard C++ Foundation; the committees repositories are under [github.com/*cplusplus*](https://github.com/cplusplus). Some neutral organization has to own the copyright and license to make it clear this is not being dominated by any one person or vendor. The natural entity is the Foundation, which exists to promote the use and up-to-date understanding of modern Standard C++ and the work of the committee. This follows the same pattern that isocpp.org did for the [C++ FAQ](https://isocpp.org/faq), which was initially the work of Bjarne Stroustrup, Marshall Cline, and Herb Sutter and contributed to the open project in the same way.
### <a name="Faq-cpp98"></a> FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version?
No. These guidelines are about how to best use Standard C++14 (and, if you have an implementation available, the Concepts Lite Technical Specification) and write code assuming you have a modern conforming compiler.
### <a name="Faq-language-extensions"></a> FAQ.9: Do these guidelines propose new language features?
No. These guidelines are about how to best use Standard C++14 + the Concepts Lite Technical Specification, and they limit themselves to recommending only those features.
### <a name="Faq-gsl"></a> FAQ.50: What is the GSL (guideline support library)?
The GSL is the small set of types and aliases specified in these guidelines. As of this writing, their specification herein is too sparse; we plan to add a WG21-style interface specification to ensure that different implementations agree, and to propose as a contribution for possible standardization, subject as usual to whatever the committee decides to accept/improve/alter/reject.
### <a name="Faq-msgsl"></a> FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL?
No. That is just a first implementation contributed by Microsoft. Other implementations by other vendors are encouraged, as are forks of and contributions to that implementation. As of this writing one week into the public project, at least one GPLv3 open source implementation already exists. We plan to produce a WG21-style interface specification to ensure that different implementations agree.
### <a name="Faq-gsl-implementation"></a> FAQ.52: Why not supply an actual GSL implementation in/with these guidelines?
We are reluctant to bless one particular implementation because we do not want to make people think there is only one, and inadvertently stifle parallel implementations. And if these guidelines included an actual implementation, then whoever contributed it could be mistakenly seen as too influential. We prefer to follow the long-standing approach of the committee, namely to specify interfaces, not implementations. But at the same time we want at least one implementation available; we hope for many.
### <a name="Faq-boost"></a> FAQ.53: Why werent the GSL types proposed through Boost?
Because we want to use them immediately, and because they are temporary in that we want to retire them as soon as types that fill the same needs exist in the standard library.
### <a name="Faq-gsl-iso"></a> FAQ.54: Has the GSL (guideline support library) been approved by the ISO C++ standards committee?
No. The GSL exists only to supply a few types and aliases that are not currently in the standard library. If the committee decides on standardized versions (of these or other types that fill the same need) then they can be removed from the GSL.
### <a name="Faq-gsl-string-view"></a> FAQ.55: If youre using the standard types where available, why is the GSL `string_view` different from the `string_view` in the Library Fundamentals 1 Technical Specification? Why not just use the committee-approved `string_view`?
Because `string_view` is still undergoing standardization, and is in a state for public review input to improve it. Types that appear in Technical Specifications (TSes) are not yet part of the International Standard (IS), and one reason they are put in TSes first is to gain experience with the feature before they are cast in a final form to become part of the standard. Some of the GSL authors are contributing what we have learned about `string_view` in the process of developing these guidelines, and a discussion of the differences, as a paper for the next ISO meeting for consideration along with all the other similar papers for the committee to consider as it decides on the final form of this feature.
### <a name="Faq-gsl-owner"></a> FAQ.56: Is `owner` the same as the proposed `observer_ptr`?
No. `owner` owns, is an alias, and can be applied to any indirection type. The main intent of `observer_ptr` is to signify a *non*-owning pointer.
### <a name="Faq-gsl-stack-array"></a> FAQ.57: Is `stack_array` the same as the standard `array`?
No. `stack_array` is guaranteed to be allocated on the stack. Although a `std::array` contains its storage directly inside itself, the `array` object can be put anywhere, including the heap.
### <a name="Faq-gsl-dyn-array"></a> FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`?
No. `dyn_array` is not resizable, and is a safe way to refer to a heap-allocated fixed-size array. Unlike `vector`, it is intended to replace array-`new[]`. Unlike the `dynarray` that has been proposed in the committee, this does not anticipate compiler/language magic to somehow allocate it on the stack when it is a member of an object that is allocated on the stack; it simply refers to a "dynamic" or heap-based array.
### <a name="Faq-gsl-expects"></a> FAQ.59: Is `Expects` the same as `assert`?
No. It is a placeholder for language support for contract preconditions.
### <a name="Faq-gsl-ensures"></a> FAQ.60: Is `Ensures` the same as `assert`?
No. It is a placeholder for language support for contract postconditions.
# <a name="S-libraries"></a> Appendix A: Libraries
This section lists recommended libraries, and explicitly recommends a few.
??? Suitable for the general guide? I think not ???
# <a name="S-modernizing"></a> Appendix B: Modernizing code
Ideally, we follow all rules in all code.
@@ -12801,7 +12724,6 @@ The guidelines are not a random set of unrelated rules where you can randomly pi
We would dearly love to hear about experience and about tools used.
Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools.
# <a name="S-discussion"></a> Appendix C: Discussion
This section contains follow-up material on rules and sets of rules.
@@ -12824,7 +12746,6 @@ Member variables are always initialized in the order they are declared in the cl
, email(first + "." + last + "@acme.com") // BAD: first and last not yet constructed
{}
In this example, `email` will be constructed before `first` and `last` because it is declared first. That means its constructor will attempt to use `first` and `last` too soon -- not just before they are set to the desired values, but before they are constructed at all.
If the class definition and the constructor body are in separate files, the long-distance influence that the order of member variable declarations has over the constructor's correctness will be even harder to spot.
@@ -12889,9 +12810,6 @@ In summary, no post-construction technique is perfect. The worst techniques dodg
**References**: [[Alexandrescu01]](#Alexandrescu01) §3, [[Boost]](#Boost), [[Dewhurst03]](#Dewhurst03) §75, [[Meyers97]](#Meyers97) §46, [[Stroustrup00]](#Stroustrup00) §15.4.3, [[Taligent94]](#Taligent94)
### <a name="Sd-dtor"></a> Discussion: Make base class destructors public and virtual, or protected and nonvirtual
Should destruction behave virtually? That is, should destruction through a pointer to a `base` class should be allowed? If yes, then `base`'s destructor must be public in order to be callable, and virtual otherwise calling it results in undefined behavior. Otherwise, it should be protected so that only derived classes can invoke it in their own destructors, and nonvirtual since it doesn't need to behave virtually virtual.
@@ -12900,36 +12818,32 @@ Should destruction behave virtually? That is, should destruction through a point
The common case for a base class is that it's intended to have publicly derived classes, and so calling code is just about sure to use something like a `shared_ptr<base>`:
```
class base {
public:
class base {
public:
~base(); // BAD, not virtual
virtual ~base(); // GOOD
// ...
};
};
class derived : public base { /*...*/ };
class derived : public base { /*...*/ };
{
{
shared_ptr<base> pb = make_shared<derived>();
// ...
} // ~pb invokes correct destructor only when ~base is virtual
```
} // ~pb invokes correct destructor only when ~base is virtual
In rarer cases, such as policy classes, the class is used as a base class for convenience, not for polymorphic behavior. It is recommended to make those destructors protected and nonvirtual:
```
class my_policy {
public:
class my_policy {
public:
virtual ~my_policy(); // BAD, public and virtual
protected:
protected:
~my_policy(); // GOOD
// ...
};
};
template<class Policy>
class customizable : Policy { /*...*/ }; // note: private inheritance
```
template<class Policy>
class customizable : Policy { /*...*/ }; // note: private inheritance
##### Note
@@ -12965,81 +12879,72 @@ In this rare case, you could make the destructor public and nonvirtual but clear
In general, however, avoid concrete base classes (see Item 35). For example, `unary_function` is a bundle-of-typedefs that was never intended to be instantiated standalone. It really makes no sense to give it a public destructor; a better design would be to follow this Item's advice and give it a protected nonvirtual destructor.
**References**: [[C++CS]](#C++CS) Item 50, [[Cargill92]](#Cargill92) pp. 77-79, 207¸ [[Cline99]](#Cline99) §21.06, 21.12-13¸ [[Henricson97]](#Henricson97) pp. 110-114¸ [[Koenig97]](#Koenig97) Chapters 4, 11¸ [[Meyers97]](#Meyers97) §14¸ [[Stroustrup00]](#Stroustrup00) §12.4.2¸ [[Sutter02]](#Sutter02) §27¸ [[Sutter04]](#Sutter04) §18
### <a name="Sd-noexcept"></a> Discussion: Usage of noexecpt
???
### <a name="Sd-never-fail"></a> Discussion: Destructors, deallocation, and swap must never fail
Never allow an error to be reported from a destructor, a resource deallocation function (e.g., `operator delete`), or a `swap` function using `throw`. It is nearly impossible to write useful code if these operations can fail, and even if something does go wrong it nearly never makes any sense to retry. Specifically, types whose destructors may throw an exception are flatly forbidden from use with the C++ standard library. Most destructors are now implicitly `noexcept` by default.
##### Example
```
class nefarious {
public:
class nefarious {
public:
nefarious() { /* code that could throw */ } // ok
~nefarious() { /* code that could throw */ } // BAD, should not throw
// ...
};
```
};
1. `nefarious` objects are hard to use safely even as local variables:
```
void test(string& s) {
void test(string& s) {
nefarious n; // trouble brewing
string copy = s; // copy the string
} // destroy copy and then n
```
} // destroy copy and then n
Here, copying `s` could throw, and if that throws and if `n`'s destructor then also throws, the program will exit via `std::terminate` because two exceptions can't be propagated simultaneously.
2. Classes with `nefarious` members or bases are also hard to use safely, because their destructors must invoke `nefarious`' destructor, and are similarly poisoned by its poor behavior:
```
class innocent_bystander {
class innocent_bystander {
nefarious member; // oops, poisons the enclosing class's destructor
// ...
};
};
void test(string& s) {
void test(string& s) {
innocent_bystander i; // more trouble brewing
string copy = s; // copy the string
} // destroy copy and then i
```
} // destroy copy and then i
Here, if constructing `copy2` throws, we have the same problem because `i`'s destructor now also can throw, and if so we'll invoke `std::terminate`.
3. You can't reliably create global or static `nefarious` objects either:
```
static nefarious n; // oops, any destructor exception can't be caught
```
static nefarious n; // oops, any destructor exception can't be caught
4. You can't reliably create arrays of `nefarious`:
```
void test() {
void test() {
std::array<nefarious, 10> arr; // this line can std::terminate(!)
}
```
The behavior of arrays is undefined in the presence of destructors that throw because there is no reasonable rollback behavior that could ever be devised. Just think: What code can the compiler generate for constructing an `arr` where, if the fourth object's constructor throws, the code has to give up and in its cleanup mode tries to call the destructors of the already-constructed objects... and one or more of those destructors throws? There is no satisfactory answer.
5. You can't use `Nefarious` objects in standard containers:
```
std::vector<nefarious> vec(10); // this is line can std::terminate()
```
std::vector<nefarious> vec(10); // this is line can std::terminate()
The standard library forbids all destructors used with it from throwing. You can't store `nefarious` objects in standard containers or use them with any other part of the standard library.
##### Note
These are key functions that must not fail because they are necessary for the two key operations in transactional programming: to back out work if problems are encountered during processing, and to commit work if no problems occur. If there's no way to safely back out using no-fail operations, then no-fail rollback is impossible to implement. If there's no way to safely commit state changes using a no-fail operation (notably, but not limited to, `swap`), then no-fail commit is impossible to implement.
@@ -13053,12 +12958,10 @@ Consider the following advice and requirements found in the C++ Standard:
Deallocation functions, including specifically overloaded `operator delete` and `operator delete[]`, fall into the same category, because they too are used during cleanup in general, and during exception handling in particular, to back out of partial work that needs to be undone.
Besides destructors and deallocation functions, common error-safety techniques rely also on `swap` operations never failing--in this case, not because they are used to implement a guaranteed rollback, but because they are used to implement a guaranteed commit. For example, here is an idiomatic implementation of `operator=` for a type `T` that performs copy construction followed by a call to a no-fail `swap`:
```
T& T::operator=( const T& other ) {
T& T::operator=( const T& other ) {
auto temp = other;
swap(temp);
}
```
}
(See also Item 56. ???)
@@ -13066,12 +12969,8 @@ Fortunately, when releasing a resource, the scope for failure is definitely smal
When using exceptions as your error handling mechanism, always document this behavior by declaring these functions `noexcept`. (See Item 75.)
**References**: [[C++CS]](#C++CS) Item 51; [[C++03]](#C++03) §15.2(3), §17.4.4.8(3)¸ [[Meyers96]](#Meyers96) §11¸ [[Stroustrup00]](#Stroustrup00) §14.4.7, §E.2-4¸ [[Sutter00]](#Sutter00) §8, §16¸ [[Sutter02]](#Sutter02) §18-19
## <a name="Sd-consistent"></a> Define Copy, move, and destroy consistently
##### Reason
@@ -13104,7 +13003,6 @@ If you define a move constructor, you must also define a move assignment operato
x x2 = x1; // ok
x2 = x1; // pitfall: either fails to compile, or does something suspicious
If you define a destructor, you should not use the compiler-generated copy or move operation; you probably need to define or suppress copy and/or move.
class X {
@@ -13144,7 +13042,6 @@ If you define any of the copy constructor, copy assignment operator, or destruct
##### Note
If you need to define any of these five functions, it means you need it to do more than its default behavior--and the five are asymmetrically interrelated. Here's how:
* If you write/disable either of the copy constructor or the copy assignment operator, you probably need to do the same for the other: If one does "special" work, probably so should the other because the two functions should have similar effects. (See Item 53, which expands on this point in isolation.)
@@ -13161,8 +13058,6 @@ In a class holding a reference, you likely need to write the copy constructor an
**References**: [[C++CS]](#C++CS) Item 52; [[Cline99]](#Cline99) §30.01-14¸ [[Koenig97]](#Koenig97) §4¸ [[Stroustrup00]](#Stroustrup00) §5.5, §10.4¸ [[SuttHysl04b]](#SuttHysl04b)
Resource management rule summary:
* [Provide strong resource safety; that is, never leak anything that you think of as a resource](#Cr-safety)