Modern C++
Tyler Howard
DevTricks 08/11/15
Brief history:
- Made in 1979 ("C With Classes")
- Revised in 1983 (Renamed to C++)
- Commercial release in 1985
- Mostly object-oriented features in this era
- OOP, virtual functions, multiple inheritance, etc.
Brief history:
- Standardized for first time with C++98
- STL (Standard Template Library) included
- C++03: minor updates to C++98
- No changes to core, only addressed defects
- TR1 (Library Technical Report) in 2005
- Draft document, not a standard
- Emphasis on template programming and data structures
Brief history:
- C++11 standard released
- Major revision to standard
- 13 years since anything really "new" (C++98)
- C++14: similar to C++03, fixes to C++11
Basically the rest of this talk's topic
C++11 and C++14
- More tools to let the compiler do the work for you
- Cleaner syntax and usability enhancements
- Cross-platform threading support
Memory Management
- Better pointers known as "smart pointers"
-
unique_ptr<T>
-
shared_ptr<T>
-
weak_ptr<T>
-
- More like pointer wrapper
- Reference counting
- Overloaded = operators
Why it's awesome:
- Basically interchangeable with old pointers
- Easy to update old code
- Maintains Resource Acquisition Is Initialization (RAII)
- Reference-counted, not garbage-collected
- Immediately release resources when no longer needed
- Removes burden from programmer
- i.e. never manually use "delete" again
Compare:
void someFunction() { int* p = new int(5); // ... delete p; }
Compare:
void someFunction() { shared_ptr<int> p(new int(5)); // ... //implicit ~p on function return }
Type Safety
- New tools to increase code re-use:
-
auto
-
decltype
-
- Compiler deduces type of variables when possible
- Reduces verbosity of code
auto
- Used in place of type declaration
- e.g. instead of
-
int x = 5;
-
- use:
-
auto x = 5; //x is still int
-
decltype
- "Getter" for type
- Not realtime reflection, just deferred deduction
- Short example:
int x = 5; decltype(x) y = x; //y is an int
More practical use:
- Write function once for multiple data types
- Cleaner syntax than with templates
auto addSelf(auto x) { return x + x; } //Compiler generates versions for both: addSelf(5); addSelf(std::string("Repeat"));
More practical use:
- Just straight-up saves on typing
std::vector<std:pair<int, int>>::iterator it = tuples.begin();
//identical to:
auto it = tuples.begin();
For-range
Syntax of "for" expanded:
for(int i = 0; i < indices.size(); ++i) { x = indices[i]; }
equivalent to:
for(int x : indices)
Works for: C-style arrays, initializer lists, types with iterators
And more!
- Threads in standard library
- Cross-platform at a language level now
- Functions as data types
- Instead of function pointers
- Relatedly, lambda/anonymous functions
Questions?
deck
By tdhoward
deck
- 605