SlideShare a Scribd company logo
What’s New in
C++ 11?
Dina Goldshtein
she codes(jlm);
July 2014
Agenda
 C++ History
 C++ 11
 Usability
 Standard library
 C++ 14
Some History
• First real standard
• What is usually taught at universityC++98
• Bug fixes
C++03
• Smart pointers
• Regexes
• Hashmap and the likes
C++TR1
• We’ll learn today
C++11
• Minor language enhancements
C++14
Usability
List Initialization and Uniform
Initialization
struct MyStr
{
int i;
string s;
};
 Before
vector<MyStr> vec(2);
vec[0].i = 1;
vec[0].s = "1";
vec[1].i = 2;
vec[1].s = "2";
 After
MyStr myStr = { 1, "1" };
vector<MyStr> vec1 = {{ 1, "1" },{ 2, "2" }};
vector<MyStr> vec2{{ 1, "1" },{ 2, "2" }};
Support Uniform Initialization
struct Settings {
map<string, int> m;
Settings(
initializer_list<pair<string, int>> s) {
for (const auto& p : s)
{
m.insert(p);
}
}
};
Type Inference
std::map<std::string,
std::vector<std::string>> m = ...;
 Before
for(std::map<std::string,
std::vector<std::string>>::const_iterator
i = m.cbegin();
i != m.cend();
++i){ }
 After
for(auto i = m.cbegin(); i != m.cend(); ++i){}
auto Quiz
int getInt();
int& getIntReference();
const int& getConstIntReference();
auto i = getInt();
auto ir = getIntReference();
auto cir = getConstIntReference();
auto& i = getInt();
auto& ir = getIntReference();
auto& cir = getConstIntReference();
const auto& i = getInt();
const auto& ir = getIntReference();
const auto& cir = getConstIntReference();
Range-Based Loops
vector<MyStr> vec1 {{ 1, "1" },{ 2, "2" }};
 Before
for (size_t i = 0; i < vec.size(); ++i) {
const MyStr& s = vec[i];
// do something with s
}
 After
for (const auto& s : vec) {
// do something with s
}
More Range-Based Loops
map<string,vector<string>> m = ...;
 Before
for(map<string,
vector<string>>::iterator pi =
m.begin(); pi != m.end(); ++pi) {
pair<const string,
vector<string>>& pair = *pi;
}
 After
for (auto& pair : map) { }
Support Range-Based Loops
struct MyArr {
int arr[100];
int size = 0;
void push_back(int e) { arr[size++] = e; }
int& operator[](int i) { return arr[i]; }
};
namespace std {
int* begin(MyArr& a){ return &a.arr[0]; }
int* end(MyArr& a){ return &a.arr[a.size]; }
}
Lambda Functions
[]
Capture
List
()
Parameters
{}
Code
();
Invocation
Lambdas Shorten Code
vector<MyStr> vec = ...;
 Before
struct MyStrComp {
bool operator()(const MyStr& s1,
const MyStr& s2) const {return s1.i>s2.i;}
};
sort(vec.begin(), vec.end(), MyStrComp());
 After
sort(vec.begin(), vec.end(),
[](const MyStr& s1, const MyStr& s2) {
return s1.i > s2.i;
});
Reference Capturing
vector<int> input{ 1, 2, 3, ... };
vector<int> primes;
for_each(input.cbegin(), input.cend(),
[&primes](int n)
{
if (isPrime(n))
primes.push_back(n);
});
for_each(input.cbegin(), input.cend(),
[=primes](int n)
{
if (isPrime(n))
primes.push_back(n); //doesn't compile
});
Non-Static Data Initialization
Before
class Complex {
public:
Complex() {
_x = _y = 0;
}
Complex(double x) :_x(x) {
_y = 0;
}
Complex(double x, double y)
: _x(x), _y(y) {}
private:
double _x;
double _y;
};
After
class Complex {
public:
Complex(double x) :_x(x) { }
Complex(double x, double y)
: _x(x), _y(y) {}
private:
double _x = 0;
double _y = 0;
};
Delegating Constructor
Before
class Complex {
public:
Complex() {
init();
}
Complex(double x) {
init(); _x = x;
}
Complex(double x, double y) {
init();
_x = x; _y = y;
}
private:
double _x;
double _y;
void init() { _x = _y = 0; }
};
After
class Complex {
public:
Complex() : Complex(0) { }
Complex(double x)
: Complex(x, 0) { }
Complex(double x, double y) {
_x = x;
_y = y;
}
private:
double _x;
double _y;
};
Standard Library
Upgrades to Current Library
 Significant performance improvements when
previously copying was required
 Internal memory management
 Return containers by value
 Eliminate need to copy elements when inserting
into containers
Oh man…
struct _StockThreadParams {
map<string, double>& stocks;
string stockName;
CRITICAL_SECTION* lock;
};
DWORD WINAPI _StockThread(LPVOID p) {
_StockThreadParams* param = (_StockThreadParams*)p;
double stockValue = getStock(param->stockName);
EnterCriticalSection(param->lock);
param->stocks[param->stockName] = stockValue;
LeaveCriticalSection(param->lock);
return 0;
}
void useOldThread() {
CRITICAL_SECTION lock;
InitializeCriticalSection(&lock);
map<string, double> stocks;
_StockThreadParams param1{ stocks, "apple", &lock };
_StockThreadParams param2{ stocks, "microsoft", &lock };
HANDLE threads[] = {
CreateThread(NULL, 0, _StockThread, &param1, 0, NULL),
CreateThread(NULL, 0, _StockThread, &param2, 0, NULL)
};
WaitForMultipleObjects(2, threads, TRUE, INFINITE);
DeleteCriticalSection(&lock);
}
Standard Multi-Threading
mutex m;
map<string, double> stocks;
thread ta([&] {
auto val = getStock("apple");
lock_guard<mutex> lg(m);
stocks["apple"] = val;
});
thread tm([&]{
auto val = getStock("microsoft");
lock_guard<mutex> lg(m);
stocks["microsoft"] = val;
});
ta.join(); tm.join();
Tuple Types
tuple<int, string, string> httpResponse =
getPage("google.com");
string body = get<2>(httpResponse);
int status;
string header;
tie(status, header, ignore) =
getPage("yahoo.com");
Smart Pointers
 No reason to use new or delete any more...
 unique_ptr
 Use when only a single reference is allowed at
the same time
 Passing a unique reference discredits the
original one
 shared_ptr
 Use when you want to share the instance
between multiple objects
 weak_ptr
 Use to break up cycles
Unique Pointers
 Passing by value or returning from function
invalidates the previous reference
 This is the most common case
 Any private member
 Factory methods
 Why not simply use values instead?
Shared Pointers
 Counts references to find out when to delete a
raw pointer
struct employee {/*...*/};
struct manager {
vector<shared_ptr<employee>> employees;
} bob;
struct payroll_system {
map<shared_ptr<employee>,double> salaries;
} payroll;
shared_ptr<employee> kate(new employee(/**/));
payroll.salaries[kate] = 600000.0;
bob.employees.push_back(kate);
Weak Pointers
 Shared pointers don’t solve the problem of
cyclic references
struct manager {
std::vector<shared_ptr<employee>> employees;
};
struct employee {
std::weak_ptr<manager> manager;
void request_leave() {
if (auto m = manager.lock())
{ m->request_leave(*this); }
} // m is shared_ptr<manager>, might be null
};
Hash Tables
 Better performance!
 std::unordered_set
 std::unordered_multiset
 std::unordered_map
 std::unordered_multimap
For the Mathematicians
 Random distributions:
 uniform_int
 uniform_real
 bernoulli
 binomial
 geometric
 negative_binomial
 poisson
 exponential
 Gamma
 Weibull
 extreme_value
 normal
 lognormal
 chi_squared
 cauchy
 fisher_f
 student_t
 discrete
 piecewise_constant
 piecewise_linear
More Goodies in Future C++14
 Generic lambda functions
auto lambda = [](auto x, auto y) {
return x + y;
};
 Return-type inference
auto foo(int i) {
if (i == 1) return i; // return int
else return foo(i - 1) + i;
}
 STL enhancements:
 Shared mutexes and locking
 Tuple addressing via type
More Stuff You Should Know
 Templates
 STL algorithms
 Rvalue references and move constructors
 Variadic templates
Summary
 C++ History
 C++ 11
 Usability
 Standard library
 C++ 14
Questions?
Exercise
 Modernize some real open-source code!
 Download code from here:
http://bit.ly/1ryNgji
 Go crazy!

More Related Content

What's hot

C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
Olve Maudal
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
Syed Hassan Kazmi
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
Sasha Goldshtein
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
Jan Rüegg
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
CyberPlusIndia
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 
C++11
C++11C++11
C++ 11
C++ 11C++ 11
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Modern C++
Modern C++Modern C++
Modern C++
Michael Clark
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Linked list
Linked listLinked list
Linked list
somuinfo123
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
fawzmasood
 

What's hot (20)

C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
Memory management in c++
Memory management in c++Memory management in c++
Memory management in c++
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
C++ references
C++ referencesC++ references
C++ references
 
C++11
C++11C++11
C++11
 
C++ 11
C++ 11C++ 11
C++ 11
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Modern C++
Modern C++Modern C++
Modern C++
 
Modern C++
Modern C++Modern C++
Modern C++
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Linked list
Linked listLinked list
Linked list
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 

Similar to What's New in C++ 11/14?

Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
Yung-Yu Chen
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
Ilio Catallo
 
Bw14
Bw14Bw14
ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdf
Chen-Hung Hu
 
Chapter 2
Chapter 2Chapter 2
C++ Secure Programming
C++ Secure ProgrammingC++ Secure Programming
C++ Secure Programming
Marian Marinov
 
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
 
Architecture for scalable Angular applications
Architecture for scalable Angular applicationsArchitecture for scalable Angular applications
Architecture for scalable Angular applications
Paweł Żurowski
 
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
Fwdays
 
Functional C++
Functional C++Functional C++
Functional C++
Kevlin Henney
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
K Hari Shankar
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
Cloudera, Inc.
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
Vani Kandhasamy
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 

Similar to What's New in C++ 11/14? (20)

Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Bw14
Bw14Bw14
Bw14
 
ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdf
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
C++ Secure Programming
C++ Secure ProgrammingC++ Secure Programming
C++ Secure Programming
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Architecture for scalable Angular applications
Architecture for scalable Angular applicationsArchitecture for scalable Angular applications
Architecture for scalable Angular applications
 
Unit 3
Unit 3 Unit 3
Unit 3
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
Functional C++
Functional C++Functional C++
Functional C++
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 

More from Dina Goldshtein

How Does the Internet Work? (Wix she codes; branch)
How Does the Internet Work? (Wix she codes; branch)How Does the Internet Work? (Wix she codes; branch)
How Does the Internet Work? (Wix she codes; branch)
Dina Goldshtein
 
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Dina Goldshtein
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
Dina Goldshtein
 
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Dina Goldshtein
 
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
Dina Goldshtein
 
Look Mommy, no GC! (.NET Summit 2017)
Look Mommy, no GC! (.NET Summit 2017)Look Mommy, no GC! (.NET Summit 2017)
Look Mommy, no GC! (.NET Summit 2017)
Dina Goldshtein
 
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Dina Goldshtein
 
Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)
Dina Goldshtein
 
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
Dina Goldshtein
 
Look Mommy, no GC! (SDP May 2017)
Look Mommy, no GC! (SDP May 2017)Look Mommy, no GC! (SDP May 2017)
Look Mommy, no GC! (SDP May 2017)
Dina Goldshtein
 
Look Mommy, No GC! (Codecamp Iasi 2017)
Look Mommy, No GC! (Codecamp Iasi 2017)Look Mommy, No GC! (Codecamp Iasi 2017)
Look Mommy, No GC! (Codecamp Iasi 2017)
Dina Goldshtein
 
Look Mommy, No GC! (NDC London 2017)
Look Mommy, No GC! (NDC London 2017)Look Mommy, No GC! (NDC London 2017)
Look Mommy, No GC! (NDC London 2017)
Dina Goldshtein
 
How does the Internet Work?
How does the Internet Work?How does the Internet Work?
How does the Internet Work?
Dina Goldshtein
 
How does the Internet Work?
How does the Internet Work?How does the Internet Work?
How does the Internet Work?
Dina Goldshtein
 
Things They Don’t Teach You @ School
Things They Don’t Teach You @ SchoolThings They Don’t Teach You @ School
Things They Don’t Teach You @ School
Dina Goldshtein
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
Dina Goldshtein
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Dina Goldshtein
 

More from Dina Goldshtein (17)

How Does the Internet Work? (Wix she codes; branch)
How Does the Internet Work? (Wix she codes; branch)How Does the Internet Work? (Wix she codes; branch)
How Does the Internet Work? (Wix she codes; branch)
 
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
Self-Aware Applications: Automatic Production Monitoring (SDP November 2017)
 
Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)Look Mommy, No GC! (TechDays NL 2017)
Look Mommy, No GC! (TechDays NL 2017)
 
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
Self-Aware Applications: Automatic Production Monitoring (TechDays NL 2017)
 
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
ETW - Monitor Anything, Anytime, Anywhere (Velocity NYC 2017)
 
Look Mommy, no GC! (.NET Summit 2017)
Look Mommy, no GC! (.NET Summit 2017)Look Mommy, no GC! (.NET Summit 2017)
Look Mommy, no GC! (.NET Summit 2017)
 
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
Self-Aware Applications: Automatic Production Monitoring (NDC Sydney 2017)
 
Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)Look Mommy, no GC! (BrightSource)
Look Mommy, no GC! (BrightSource)
 
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
ETW - Monitor Anything, Anytime, Anywhere (NDC Oslo 2017)
 
Look Mommy, no GC! (SDP May 2017)
Look Mommy, no GC! (SDP May 2017)Look Mommy, no GC! (SDP May 2017)
Look Mommy, no GC! (SDP May 2017)
 
Look Mommy, No GC! (Codecamp Iasi 2017)
Look Mommy, No GC! (Codecamp Iasi 2017)Look Mommy, No GC! (Codecamp Iasi 2017)
Look Mommy, No GC! (Codecamp Iasi 2017)
 
Look Mommy, No GC! (NDC London 2017)
Look Mommy, No GC! (NDC London 2017)Look Mommy, No GC! (NDC London 2017)
Look Mommy, No GC! (NDC London 2017)
 
How does the Internet Work?
How does the Internet Work?How does the Internet Work?
How does the Internet Work?
 
How does the Internet Work?
How does the Internet Work?How does the Internet Work?
How does the Internet Work?
 
Things They Don’t Teach You @ School
Things They Don’t Teach You @ SchoolThings They Don’t Teach You @ School
Things They Don’t Teach You @ School
 
HTML5 Canvas
HTML5 CanvasHTML5 Canvas
HTML5 Canvas
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 

Recently uploaded

Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

What's New in C++ 11/14?

  • 1. What’s New in C++ 11? Dina Goldshtein she codes(jlm); July 2014
  • 2. Agenda  C++ History  C++ 11  Usability  Standard library  C++ 14
  • 3. Some History • First real standard • What is usually taught at universityC++98 • Bug fixes C++03 • Smart pointers • Regexes • Hashmap and the likes C++TR1 • We’ll learn today C++11 • Minor language enhancements C++14
  • 5. List Initialization and Uniform Initialization struct MyStr { int i; string s; };  Before vector<MyStr> vec(2); vec[0].i = 1; vec[0].s = "1"; vec[1].i = 2; vec[1].s = "2";  After MyStr myStr = { 1, "1" }; vector<MyStr> vec1 = {{ 1, "1" },{ 2, "2" }}; vector<MyStr> vec2{{ 1, "1" },{ 2, "2" }};
  • 6. Support Uniform Initialization struct Settings { map<string, int> m; Settings( initializer_list<pair<string, int>> s) { for (const auto& p : s) { m.insert(p); } } };
  • 7. Type Inference std::map<std::string, std::vector<std::string>> m = ...;  Before for(std::map<std::string, std::vector<std::string>>::const_iterator i = m.cbegin(); i != m.cend(); ++i){ }  After for(auto i = m.cbegin(); i != m.cend(); ++i){}
  • 8. auto Quiz int getInt(); int& getIntReference(); const int& getConstIntReference(); auto i = getInt(); auto ir = getIntReference(); auto cir = getConstIntReference(); auto& i = getInt(); auto& ir = getIntReference(); auto& cir = getConstIntReference(); const auto& i = getInt(); const auto& ir = getIntReference(); const auto& cir = getConstIntReference();
  • 9. Range-Based Loops vector<MyStr> vec1 {{ 1, "1" },{ 2, "2" }};  Before for (size_t i = 0; i < vec.size(); ++i) { const MyStr& s = vec[i]; // do something with s }  After for (const auto& s : vec) { // do something with s }
  • 10. More Range-Based Loops map<string,vector<string>> m = ...;  Before for(map<string, vector<string>>::iterator pi = m.begin(); pi != m.end(); ++pi) { pair<const string, vector<string>>& pair = *pi; }  After for (auto& pair : map) { }
  • 11. Support Range-Based Loops struct MyArr { int arr[100]; int size = 0; void push_back(int e) { arr[size++] = e; } int& operator[](int i) { return arr[i]; } }; namespace std { int* begin(MyArr& a){ return &a.arr[0]; } int* end(MyArr& a){ return &a.arr[a.size]; } }
  • 13. Lambdas Shorten Code vector<MyStr> vec = ...;  Before struct MyStrComp { bool operator()(const MyStr& s1, const MyStr& s2) const {return s1.i>s2.i;} }; sort(vec.begin(), vec.end(), MyStrComp());  After sort(vec.begin(), vec.end(), [](const MyStr& s1, const MyStr& s2) { return s1.i > s2.i; });
  • 14. Reference Capturing vector<int> input{ 1, 2, 3, ... }; vector<int> primes; for_each(input.cbegin(), input.cend(), [&primes](int n) { if (isPrime(n)) primes.push_back(n); }); for_each(input.cbegin(), input.cend(), [=primes](int n) { if (isPrime(n)) primes.push_back(n); //doesn't compile });
  • 15. Non-Static Data Initialization Before class Complex { public: Complex() { _x = _y = 0; } Complex(double x) :_x(x) { _y = 0; } Complex(double x, double y) : _x(x), _y(y) {} private: double _x; double _y; }; After class Complex { public: Complex(double x) :_x(x) { } Complex(double x, double y) : _x(x), _y(y) {} private: double _x = 0; double _y = 0; };
  • 16. Delegating Constructor Before class Complex { public: Complex() { init(); } Complex(double x) { init(); _x = x; } Complex(double x, double y) { init(); _x = x; _y = y; } private: double _x; double _y; void init() { _x = _y = 0; } }; After class Complex { public: Complex() : Complex(0) { } Complex(double x) : Complex(x, 0) { } Complex(double x, double y) { _x = x; _y = y; } private: double _x; double _y; };
  • 18. Upgrades to Current Library  Significant performance improvements when previously copying was required  Internal memory management  Return containers by value  Eliminate need to copy elements when inserting into containers
  • 19. Oh man… struct _StockThreadParams { map<string, double>& stocks; string stockName; CRITICAL_SECTION* lock; }; DWORD WINAPI _StockThread(LPVOID p) { _StockThreadParams* param = (_StockThreadParams*)p; double stockValue = getStock(param->stockName); EnterCriticalSection(param->lock); param->stocks[param->stockName] = stockValue; LeaveCriticalSection(param->lock); return 0; } void useOldThread() { CRITICAL_SECTION lock; InitializeCriticalSection(&lock); map<string, double> stocks; _StockThreadParams param1{ stocks, "apple", &lock }; _StockThreadParams param2{ stocks, "microsoft", &lock }; HANDLE threads[] = { CreateThread(NULL, 0, _StockThread, &param1, 0, NULL), CreateThread(NULL, 0, _StockThread, &param2, 0, NULL) }; WaitForMultipleObjects(2, threads, TRUE, INFINITE); DeleteCriticalSection(&lock); }
  • 20. Standard Multi-Threading mutex m; map<string, double> stocks; thread ta([&] { auto val = getStock("apple"); lock_guard<mutex> lg(m); stocks["apple"] = val; }); thread tm([&]{ auto val = getStock("microsoft"); lock_guard<mutex> lg(m); stocks["microsoft"] = val; }); ta.join(); tm.join();
  • 21. Tuple Types tuple<int, string, string> httpResponse = getPage("google.com"); string body = get<2>(httpResponse); int status; string header; tie(status, header, ignore) = getPage("yahoo.com");
  • 22. Smart Pointers  No reason to use new or delete any more...  unique_ptr  Use when only a single reference is allowed at the same time  Passing a unique reference discredits the original one  shared_ptr  Use when you want to share the instance between multiple objects  weak_ptr  Use to break up cycles
  • 23. Unique Pointers  Passing by value or returning from function invalidates the previous reference  This is the most common case  Any private member  Factory methods  Why not simply use values instead?
  • 24. Shared Pointers  Counts references to find out when to delete a raw pointer struct employee {/*...*/}; struct manager { vector<shared_ptr<employee>> employees; } bob; struct payroll_system { map<shared_ptr<employee>,double> salaries; } payroll; shared_ptr<employee> kate(new employee(/**/)); payroll.salaries[kate] = 600000.0; bob.employees.push_back(kate);
  • 25. Weak Pointers  Shared pointers don’t solve the problem of cyclic references struct manager { std::vector<shared_ptr<employee>> employees; }; struct employee { std::weak_ptr<manager> manager; void request_leave() { if (auto m = manager.lock()) { m->request_leave(*this); } } // m is shared_ptr<manager>, might be null };
  • 26. Hash Tables  Better performance!  std::unordered_set  std::unordered_multiset  std::unordered_map  std::unordered_multimap
  • 27. For the Mathematicians  Random distributions:  uniform_int  uniform_real  bernoulli  binomial  geometric  negative_binomial  poisson  exponential  Gamma  Weibull  extreme_value  normal  lognormal  chi_squared  cauchy  fisher_f  student_t  discrete  piecewise_constant  piecewise_linear
  • 28. More Goodies in Future C++14  Generic lambda functions auto lambda = [](auto x, auto y) { return x + y; };  Return-type inference auto foo(int i) { if (i == 1) return i; // return int else return foo(i - 1) + i; }  STL enhancements:  Shared mutexes and locking  Tuple addressing via type
  • 29. More Stuff You Should Know  Templates  STL algorithms  Rvalue references and move constructors  Variadic templates
  • 30. Summary  C++ History  C++ 11  Usability  Standard library  C++ 14
  • 32. Exercise  Modernize some real open-source code!  Download code from here: http://bit.ly/1ryNgji  Go crazy!

Editor's Notes

  1. auto i = getInt(); // int auto ir = getIntReference(); // int auto cir = getConstIntReference(); // int auto& i = getInt(); // doesn’t compile – can’t cast int to int& auto& ir = getIntReference(); //int & auto& cir = getConstIntReference(); //const int& - why? Because that’s the way it is const auto& i = getInt(); // const int& - but don’t do this! – it’s a temporary on the stack. If you pass I to other places you might have a problem! const auto& ir = getIntReference(); // const int& const auto& cir = getConstIntReference(); const int& מה המסקנה מכל זה? שימו את ה-& ואת ה-const בעצמכם איפה שצריך ולא יהיו בלבולים. זה לא מאריך את הקוד באופן משמעותי והקוד ברור!
  2. ואם אנחנו כבר מדברים על דרכים שבהן אפשר לקצר כתיבה של לולאות אז סוף סוף יש לנו סינטקס חדש ללולאות for – סינטקס שמאפשר לנו מעבר ישיר על איברים של container במקום שימוש באיטרטור ואז ב-dereference של האיטרטור הזה. בדוגמה הזאת קיצרנו קצת את הקוד.