Stroustrup - CppCon 2015 Keynote
Stroustrup - CppCon 2015 Keynote
Bjarne Stroustrup
Morgan Stanley, Columbia University
www.stroustrup.com
Guidelines project
Produce a useful answer
Enable many people to use that answer
For most programmers, not just language experts
Please help!
1
9/21/2015
2
9/21/2015
Please help!
3
9/21/2015
4
9/21/2015
Coding rules*
Are outdated *Usual caveats
Become a drag of their users
Are specialized
but used outside their intended domain
Are not understood by their users
Enforced by dictate: Do this or else!
Require detailed language-lawyer knowledge to follow
Are not well supported by tools
Platform dependencies
Compiler dependencies
Expensive
Do not provide guidance
Telling what not to do is not enough
Stroustrup - Guidelines - CppCon'15 11
Coding guidelines
Lets build a good set!
Comprehensive
Browsable
Supported by tools (from many sources)
Suitable for gradual adoption
For modern C++
Compatibility and legacy code be damned! (initially) We aim to offer guidance
What is good modern C++?
Prescriptive
Not punitive Confused, backwards-looking
teaching is a big problem
Teachable
Rationales and examples
Flexible
Adaptable to many communities and tasks
Non-proprietary
But assembled with taste and responsiveness
Stroustrup - Guidelines - CppCon'15 12
5
9/21/2015
High-level rules
Provide a conceptual framework
Primarily for humans
Many cant be checked completely or consistently
P.1: Express ideas directly in code
P.2: Write in ISO Standard C++
P.3: Express intent
P.4: Ideally, a program should be statically type safe
P.5: Prefer compile-time checking to run-time checking
P.6: What cannot be checked at compile time should be checkable at run time
P.7: Catch run-time errors early
P.8: Don't leak any resource
P.9: Don't waste time or space
Lower-level rules
Provide enforcement
Some complete
Some heuristics
Many rely on static analysis
Some beyond our current tools
Often easy to check mechanically
Primarily for tools
To allow specific feedback to programmer
Help to unify style
Not minimal or orthogonal
F.16: Use T* or owner<T*> to designate a single object
C.49: Prefer initialization to assignment in constructors
ES.20: Always initialize an object
Stroustrup - Guidelines - CppCon'15 14
6
9/21/2015
Subset of superset
Simple sub-setting doesnt work
We need the low-level/tricky/close-to-the-hardware/error-prone/expert-only features
For implementing higher-level facilities efficiently STL
Many low-level features can be used well GSL
Use: C++
We need the standard library
Extend language with a few abstractions
Use the STL
Dont use
Add a small library (the GSL)
No new language features
Messy/dangerous/low-level features can be used to implement the GSL
Then subset
What we want is C++ on steroids
Simple, safe, flexible, and fast
Not a neutered subset
Stroustrup - Guidelines - CppCon'15 16
7
9/21/2015
8
9/21/2015
Core Rules
Some people will not be able to apply all rules
At least initially
Gradual adoption will be very common
Many people will need additional rules
For specific needs
We initially focus on the core rules
The ones we hope that everyone eventually could benefit from
The core of the core
No leaks
No dangling pointers
No type violations through pointers
9
9/21/2015
No resource leaks
We know how
Root every object in a scope
vector<T>
string
ifstream
unique_ptr<T>
shared_ptr<T>
RAII
No naked new
No naked delete
void g()
{
X* q = new X; // looks innocent enough
f(q);
// do a lot of work here
q->use(); // Ouch! Read/scramble random memory
} Stroustrup - Guidelines - CppCon'15 22
10
9/21/2015
Dangling pointers
We must eliminate dangling pointers
Or type safety is compromised
Or memory safety is compromised
Or resource safety is compromised
Eliminated by a combination of rules
Distinguish owners from non-owners
Assume raw pointers to be non-owners
Catch all attempts for a pointer to escape into a scope
enclosing its owners scope
return, throw, out-parameters, long-lived containers,
Something that holds an owner is an owner
E.g. vector<owner<int*>>, owner<int*>[],
owner
owner
For an object on the free store the owner is a pointer
pointer For an object on the stack the owner itself
For a static object the owner is itself
Stroustrup - Guidelines - CppCon'15 24
11
9/21/2015
Dangling pointers
Ensure that no pointer outlives the object it points to
void f(X* p)
{
//
delete p; // bad: delete non-owner
}
void g()
{
X* q = new X; // bad: assign object to non-owner
f(q);
// do a lot of work here
q->use(); // Make sure we never get here
} Stroustrup - Guidelines - CppCon'15 25
Note
I talk about pointers
What I say applies to anything that refers to an object
References
Containers of pointers
Smart pointers
..
12
9/21/2015
GSL: owner<T>
How do we implement ownership abstractions?
template<SemiRegular T>
class vector {
owner<T*> elem; // the anchors the allocated memory
T* space; // just a position indicator
T* end; // just a position indicator
//
};
owner<T*> is just an alias for T*
13
9/21/2015
GSL: owner<T>
How about code we cannot change?
A static analysis tool can tell us where our code mishandles ownership
Stroustrup - Guidelines - CppCon'15 29
14
9/21/2015
int* f(int* p)
{
int x = 4;
return &x; // No! would point to destroyed stack frame
return new int{7}; // OK (sort of: doesnt dangle, but returns an owner as an int*)
return p; // OK: came from caller
}
15
9/21/2015
16
9/21/2015
Other problems
Other ways of misusing pointers
Range errors: array_view<T>
nullptr dereferencing: not_null<T>
Wasteful ways of addressing pointer problems
Misuse of smart pointers
Other ways of breaking the type system (beyond the scope of this talk)
Unions
Casts
GSL - array_view<T>
Common style
void f(int* p, int n) // what is n? (How would a tool know?)
{
p[7] = 9; // OK?
for (int i=0; i<n; ++i) p[i] = 7; // OK?
}
Better
void f(array_view<int> a)
{
a[7] = 9; // OK? Checkable against a.size()
for (int& x : a) x = 7; // OK
}
17
9/21/2015
GSL - array_view<T>
Common style Better
void f(int* p, int n); void f(array_view<int> a)
int a[100]; int a[100];
// //
f(a,100); f(array_view<int>{a});
f(a,1000); // likely disaster f(a);
f({a,1000}); // easily checkable
nullptr problems
Mixing nullptr and pointers to objects
Causes confusion
Requires (systematic) checking
Caller
void f(char*);
f(nullptr); // OK?
Implementer
void f(char* p)
{
if (p==nullptr) // necessary?
//
}
Can you trust the documentation?
Compilers dont read manuals, or comments
Complexity, errors, and/or run-time cost
Stroustrup - Guidelines - CppCon'15 38
18
9/21/2015
GSL - not_null<T>
Caller
void f(not_null<char*>);
GSL - not_null<T>
not_null<T>
A simple, small class
not_null<T*> is T* except that it cannot hold nullptr
Can be used as input to analyzers
Minimize run-time checking
Checking can be debug only
For any T that can be compared to nullptr
E.g. not_null<array_view<T>>
19
9/21/2015
To summarize
Type and resource safety:
RAII (scoped objects with constructors and destructors)
No dangling pointers
No leaks (track ownership pointers)
Eliminate range errors
Eliminate nullptr dereference
That done we attack other sources of problems
Logic errors
Performance bugs
Maintenance hazards
Verbosity
Stroustrup - Guidelines - CppCon'15 41
20
9/21/2015
void use()
{
auto p = make_shared<X>{};
f(p.get()); // extract raw pointer (note: pointers do not dangle)
g(p); // mess with use count (probably a mistake)
auto q = h(make_unique<X>(p.get())); // transfer ownership to just use (a mistake)
// extract raw pointer, then wrap it and copy
q.release(); // prevent destruction
}
Stroustrup - Guidelines - CppCon'15 44
21
9/21/2015
22
9/21/2015
Rule classification
P: Philosophy
I: Interfaces
Supporting sections
F: Functions
C: Classes and class hierarchies
NL: Naming and layout
Enum: Enumerations
PER: Performance
ES: Expressions and statements
E: Error handling N: Non-Rules and myths
R: Resource management RF: References
T: Templates and generic programming Appendix A: Libraries
CP: Concurrency Appendix B: Modernizing code
The Standard library
Appendix C: Discussion
SF: Source files
To-do: Unclassified proto-rules
CPL: C-style programming
GSL: Guideline support library
Stroustrup - Guidelines - CppCon'15 47
23
9/21/2015
Current status
Available
About 350 Rules (https://github.com/isocpp/CppCoreGuidelines)
GSL for Clang, GCC, and Microsoft (https://github.com/microsoft/gsl)
First tools: October for Microsoft; ports later (November?)
MIT License
We need help
Review of rules
More examples and refinements for existing rules
Specialized rule sets
For particular application areas, projects,
For concurrency
For libraries
Continuous development
forever
Stroustrup - Guidelines - CppCon'15 50
24
9/21/2015
Questions
P: Philosophy
I: Interfaces
F: Functions Supporting sections
C: Classes and class hierarchies
Enum: Enumerations
ES: Expressions and statements NL: Naming and layout
E: Error handling PER: Performance
R: Resource management N: Non-Rules and myths
T: Templates and generic programming RF: References
CP: Concurrency
Appendix A: Libraries
The Standard library
SF: Source files Appendix B: Modernizing code
CPL: C-style programming Appendix C: Discussion
GSL: Guideline support library To-do: Unclassified proto-rules
Stroustrup - Guidelines - CppCon'15 52
25
9/21/2015
Coding guidelines
Boost Library Requirements and Guidelines
Bloomberg: BDE C++ Coding
Facebook: ???
GCC Coding Conventions
Google C++ Style Guide
JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS
Mozilla Portability Guide.
Geosoft.no: C++ Programming Style Guidelines
Possibility.com: C++ Coding Standard
SEI CERT: Secure C++ Coding Standard
High Integrity C++ Coding Standard
llvm.org/docs/CodingStandards.html
26
9/21/2015
Non-aims
Create the one true C++ subset
There can be no such marvel
Core guidelines + guidelines for specific needs
Making a totally flexible set of rules to please everybody
Our rules are not value neutral
Total freedom is chaos
We want modern C++
not everything anyone ever thought was cool and/or necessary
Turning C++ into Java, Haskell, C, or whatever
If you want Smalltalk you know where to find it
Philosophy
Attack hard problems
Resources, interfaces, bounds,
Be prescriptive
dont do that is not very helpful
Give rationale
because I say so is not very helpful
Offer machine-checkable rules
Machines are systematic, fast, and dont get bored
Dont limit generality
For most of us most of the time
Dont compromise performance
Of course
Subset of superset
Dont fiddle with subtle language rules
Stroustrup - Guidelines - CppCon'15 56
27