SlideShare une entreprise Scribd logo
1  sur  35
© 2016 Embarcadero Technologies, Inc. All rights reserved.
USEFUL C++ FEATURES YOU SHOULD BE USING
David Millington
david.millington@embarcadero.com
© 2016 Embarcadero Technologies, Inc. All rights reserved.
CONTENT
• Type inference
• Lambdas
• New containers
• Variadic templates
• Smart pointers
• And others
Not a list of C++11 , nor going into every detail - but showing
advantages. Useful even if you already use some of these (eg pre-C++11
smart pointers.)
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE
Not just auto… but let’s start with it.
auto i = 5; // i is an int
auto j = foo(); // j is whatever foo() returns
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE
Not just auto… but let’s start with it.
auto i = 5; // i is an int
auto j = foo(); // j is whatever foo() returns
Decltype too:
decltype(i) k; // k is i’s type, an int
decltype(i + 5.5f) k; // k is the type of
“i + 5.5f”, which is float
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE IN A SIMPLE TEMPLATE
template<typename A, typename B>
void foo(A a, B b) {
UNKNOWN m = a * b; // int? float? string?
}
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE IN A SIMPLE TEMPLATE
template<typename A, typename B>
void foo(A a, B b) {
auto m = a * b; // Solved.
}
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
STL provides standard iterators making algorithms applicable regardless
of the container type – eg std::find over a std::map vs
std::unordered_map.
Fine for templates – but can you take advantage of this yourself in
normal, non-templated code?
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
std::map<int, std::wstring> items;
for (std::map<int, std::wstring>::const_iterator
it = items.begin(); it != items.end(); it++)
{
}
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
std::unordered_map<int, std::wstring> items;
for (std::map<int, std::wstring>::const_iterator
it = items.begin(); it != items.end(); it++)
{
}
Won’t compile, because despite the interface (begin, end) being the
same, the iterator types are different.
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
std::unordered_map<int, std::wstring> items;
for (std::unordered_map<int,
std::wstring>::const_iterator it =
items.begin(); it != items.end(); it++)
{
}
What a mess!
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
std::map<int, std::wstring> items;
for (auto it = items.begin(); it != items.end();
it++)
{
}
std::unordered_map<int, std::wstring> items;
Works with either declaration…
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
std::unordered_map<int, std::wstring> items;
for (auto it : items)
{
}
Works regardless of the type of items
Much shorter, clearer, easier to type code
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE WHEN USING THE STL
for (std::map<int, std::wstring>::const_iterator
it = items.begin(); it != items.end(); it++)
{
}
…versus…
for (auto it : items)
{
}
Amazing.
© 2016 Embarcadero Technologies, Inc. All rights reserved.
TYPE INFERENCE
Auto:
• Reduces typing
• Remains strongly (and predictably) typed
• Useful when the type isn’t known when writing, but can be deduced
at compile time
• Allows easy changes
• More compact and clear code
Investigate decltype too, especially for templates.
© 2016 Embarcadero Technologies, Inc. All rights reserved.
LAMBDAS
std::list<int> items { 1, 2, 3 };
…
std::replace_if(items.begin(), items.end(),
???, 99);
© 2016 Embarcadero Technologies, Inc. All rights reserved.
LAMBDAS
struct ItemComparer {
private:
int m_Value;
public:
ItemComparer(const int n) : m_Value(n) {};
bool operator()(int i) const
{ return i % m_Value == 0; }
};
std::replace_if(items.begin(), items.end(),
ItemComparer(n), 99);
© 2016 Embarcadero Technologies, Inc. All rights reserved.
LAMBDAS
int n = 2;
std::replace_if(items.begin(), items.end(),
[n](int& i) { return i % n == 0; },
99);
© 2016 Embarcadero Technologies, Inc. All rights reserved.
LAMBDAS
[] The variable or capture list
() The argument list
{} Code
Making the simplest lambda
[](){}
a method that captures nothing, is passed no arguments, and does
nothing.
[n](int& i) { return i % n == 0; }
© 2016 Embarcadero Technologies, Inc. All rights reserved.
LAMBDAS
auto f = [this, n, &j](int& i)
{ return i % n == 0; };
• Neat and readable
• Inline in code
• Inlineable and performant
• Capture variables by value or reference
• Behave like an object
© 2016 Embarcadero Technologies, Inc. All rights reserved.
VARIADIC TEMPLATES
template<typename T>
T mult(T first) {
return first;
}
template<typename T, typename... Others>
T mult(T first, Others... others) {
return first * mult(others...);
}
int z = mult(1, 2, 3, 4); // z = 24
* Based on http://eli.thegreenplace.net/2014/variadic-templates-in-c/
© 2016 Embarcadero Technologies, Inc. All rights reserved.
VARIADIC TEMPLATES
std::tuple<int, float, std::string>
t { 1, 2.5, "hello"};
float v = std::get<1>(t);
© 2016 Embarcadero Technologies, Inc. All rights reserved.
SMART POINTERS
No:
Foo* foo = new Foo();
__try {
//
} __finally {
delete foo;
}
Yes (sortof):
{
scoped_ptr<Foo> foo =
new Foo();
}
^- foo is freed
© 2016 Embarcadero Technologies, Inc. All rights reserved.
SMART POINTERS
Using boost or C++11:
{
shared_ptr<Foo> foo = new Foo();
bar->myfoo = foo; // bar::myfoo is a
shared_ptr<Foo>
} // <- foo is not freed, a reference is
still held
© 2016 Embarcadero Technologies, Inc. All rights reserved.
SMART POINTERS
Using boost? Move to shared_ptr (very familiar!) and unique_ptr instead of
scoped_ptr
In general, already using them or not:
• Use unique_ptr where possible
• Use shared_ptr not out of ease but when you want to share
• Don’t expect automatic threadsafety apart from +/- refcount
• Use shared_ptr<Foo> p = make_shared<Foo>; and
make_unique<T> if available -
http://stackoverflow.com/questions/17902405/how-to-implement-make-
unique-function-in-c11
• Never write new or delete
© 2016 Embarcadero Technologies, Inc. All rights reserved.
CONTAINERS
hash_map – common, but never standardised!
Use unordered_set, unordered_map, unordered_multiset,
unordered_multimap.
© 2016 Embarcadero Technologies, Inc. All rights reserved.
ATOMIC PRIMITIVES
C++11 defines a memory model – so race conditions and odd threading
behaviour no longer undefined behaviour.
Low-level primitives in <atomic>
Generally stick to things like mutex.
© 2016 Embarcadero Technologies, Inc. All rights reserved.
STATIC ASSERTIONS
In the past, clever code & macros to get something like:
STATIC_ASSERT(x);
Now,
static_assert(sizeof(float) == 4,
"float has unexpected size");
© 2016 Embarcadero Technologies, Inc. All rights reserved.
C++BUILDER
• FireMonkey –
cross-platform UI,
native controls,
multi-device
specialization
• Similar for other
frameworks –
database, REST,
enterprise, RAD
Server…
© 2016 Embarcadero Technologies, Inc. All rights reserved.
C++BUILDER
Compilers:
• Classic BCC32
• New Clang-enhanced
Resources:
• Docwiki lists C++11 features in
‘old’ classic compiler
• And language support in new
Clang compiler (including
newer than C++11 features)
© 2016 Embarcadero Technologies, Inc. All rights reserved.
USEFUL FEATURES
Code clarity
• Auto – clearer, easier
• Lambdas – inline, readable, function
content visible where it’s used
Safety
• Smart pointers – use unique_ptr
where possible
• Static assertions
Misc
• Standardised unordered containers
• Standardised memory model – defined
(even if unexpected) behaviour
C++Builder
• Cross-platform support
• UI – specializable for different
platforms and devices. Yet you can use
native controls too.
• New compilers – Clang-based, plus our
extensions. Better language support,
better performance. Free compiler
available!
© 2016 Embarcadero Technologies, Inc. All rights reserved.
USEFUL FEATURES
Code clarity
• Auto – clearer, easier
• Lambdas – inline, readable, function
content visible where it’s used
Safety
• Smart pointers – use unique_ptr
where possible
• Static assertions
Misc
• Standardised unordered containers
• Standardised memory model – defined
(even if unexpected) behaviour
C++Builder
• Cross-platform support
• UI – specializable for different
platforms and devices. Yet you can use
native controls too.
• New compilers – Clang-based, plus our
extensions. Better language support,
better performance. Free compiler
available!
© 2016 Embarcadero Technologies, Inc. All rights reserved.
USEFUL FEATURES
Code clarity
• Auto – clearer, easier
• Lambdas – inline, readable, function
content visible where it’s used
Safety
• Smart pointers – use unique_ptr
where possible
• Static assertions
Misc
• Standardised unordered containers
• Standardised memory model – defined
(even if unexpected) behaviour
C++Builder
• Cross-platform support
• UI – specializable for different
platforms and devices. Yet you can use
native controls too.
• New compilers – Clang-based, plus our
extensions. Better language support,
better performance. Free compiler
available!
© 2016 Embarcadero Technologies, Inc. All rights reserved.
USEFUL FEATURES
Code clarity
• Auto – clearer, easier
• Lambdas – inline, readable, function
content visible where it’s used
Safety
• Smart pointers – use unique_ptr
where possible
• Static assertions
Misc
• Standardised unordered containers
• Standardised memory model – defined
(even if unexpected) behaviour
C++Builder
• Cross-platform support
• UI – specializable for different
platforms and devices. Yet you can use
native controls too.
• New compilers – Clang-based, plus our
extensions. Better language support,
better performance. Free compiler
available!
© 2016 Embarcadero Technologies, Inc. All rights reserved.
USEFUL FEATURES
Code clarity
• Auto – clearer, easier
• Lambdas – inline, readable, function
content visible where it’s used
Safety
• Smart pointers – use unique_ptr
where possible
• Static assertions
Misc
• Standardised unordered containers
• Standardised memory model – defined
(even if unexpected) behaviour
C++Builder
• Cross-platform support
• UI – specializable for different
platforms and devices. Yet you can use
native controls too.
• New compilers – Clang-based, plus our
extensions. Better language support,
better performance. Free compiler
available!
© 2016 Embarcadero Technologies, Inc. All rights reserved.
RESOURCES
• Auto
• http://thbecker.net/articles/auto_and_decltype/section_01.html
• Lambdas
• http://www.drdobbs.com/cpp/lambdas-in-c11/240168241
• Smart pointers
• http://www.acodersjourney.com/2016/05/top-10-dumb-mistakes-avoid-c-11-smart-pointers/
• Variadic templates
• http://eli.thegreenplace.net/2014/variadic-templates-in-c/
• https://www.murrayc.com/permalink/2015/12/05/modern-c-variadic-template-parameters-and-tuples/
• Static assertions
• http://stackoverflow.com/questions/1647895/what-does-static-assert-do-and-what-would-you-use-it-for
• C++ Builder
• https://www.embarcadero.com/products/cbuilder
• https://www.embarcadero.com/free-tools/ccompiler
• http://docwiki.embarcadero.com/RADStudio/Berlin/en/C++11_Language_Features_Compliance_Status
• http://docwiki.embarcadero.com/RADStudio/Berlin/en/C%2B%2B11_Features_Supported_by_RAD_Studio
_Clang-enhanced_C%2B%2B_Compilers

Contenu connexe

Tendances

Graal Tutorial at CGO 2015 by Christian Wimmer
Graal Tutorial at CGO 2015 by Christian WimmerGraal Tutorial at CGO 2015 by Christian Wimmer
Graal Tutorial at CGO 2015 by Christian Wimmer
Thomas Wuerthinger
 
Titanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceTitanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performance
omorandi
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Thomas Wuerthinger
 
Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...
Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...
Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...
mfrancis
 

Tendances (20)

EclipseCon France 2016 - Sirius 4.0: Let me Sirius that for you!
EclipseCon France 2016 - Sirius 4.0: Let me Sirius that for you!EclipseCon France 2016 - Sirius 4.0: Let me Sirius that for you!
EclipseCon France 2016 - Sirius 4.0: Let me Sirius that for you!
 
Java and Serverless - A Match Made In Heaven, Part 1
Java and Serverless - A Match Made In Heaven, Part 1Java and Serverless - A Match Made In Heaven, Part 1
Java and Serverless - A Match Made In Heaven, Part 1
 
Randstad Docker meetup - Serverless
Randstad Docker meetup - ServerlessRandstad Docker meetup - Serverless
Randstad Docker meetup - Serverless
 
Graal VM: Multi-Language Execution Platform
Graal VM: Multi-Language Execution PlatformGraal VM: Multi-Language Execution Platform
Graal VM: Multi-Language Execution Platform
 
Graal Tutorial at CGO 2015 by Christian Wimmer
Graal Tutorial at CGO 2015 by Christian WimmerGraal Tutorial at CGO 2015 by Christian Wimmer
Graal Tutorial at CGO 2015 by Christian Wimmer
 
Titanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceTitanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performance
 
Smart Internationalization assistance and resource translation tools
Smart Internationalization assistance and resource translation toolsSmart Internationalization assistance and resource translation tools
Smart Internationalization assistance and resource translation tools
 
JavaScript for ABAP Programmers - 1/7 Introduction
JavaScript for ABAP Programmers - 1/7 IntroductionJavaScript for ABAP Programmers - 1/7 Introduction
JavaScript for ABAP Programmers - 1/7 Introduction
 
import data from Oracle Database into Python Pandas Dataframe
import data from Oracle Database into Python Pandas Dataframeimport data from Oracle Database into Python Pandas Dataframe
import data from Oracle Database into Python Pandas Dataframe
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
 
Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...
Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...
Workflow for Development, Release and Versioning with OSGi / bndtools- Real W...
 
Top 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | EdurekaTop 10 Dying Programming Languages in 2020 | Edureka
Top 10 Dying Programming Languages in 2020 | Edureka
 
Sitecore on containers and AKS
Sitecore on containers and AKSSitecore on containers and AKS
Sitecore on containers and AKS
 
Graal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them AllGraal and Truffle: One VM to Rule Them All
Graal and Truffle: One VM to Rule Them All
 
Micro-Benchmarking Considered Harmful
Micro-Benchmarking Considered HarmfulMicro-Benchmarking Considered Harmful
Micro-Benchmarking Considered Harmful
 
Building advanced Chats Bots and Voice Interactive Assistants - Stève Sfartz ...
Building advanced Chats Bots and Voice Interactive Assistants - Stève Sfartz ...Building advanced Chats Bots and Voice Interactive Assistants - Stève Sfartz ...
Building advanced Chats Bots and Voice Interactive Assistants - Stève Sfartz ...
 
REST API Doc Best Practices
REST API Doc Best PracticesREST API Doc Best Practices
REST API Doc Best Practices
 
Sitecore loves containers
Sitecore loves containersSitecore loves containers
Sitecore loves containers
 
GraphPipe - Blazingly Fast Machine Learning Inference by Vish Abrams
GraphPipe - Blazingly Fast Machine Learning Inference by Vish AbramsGraphPipe - Blazingly Fast Machine Learning Inference by Vish Abrams
GraphPipe - Blazingly Fast Machine Learning Inference by Vish Abrams
 
Java EE Arquillian Testing with Docker & The Cloud
Java EE Arquillian Testing with Docker & The CloudJava EE Arquillian Testing with Docker & The Cloud
Java EE Arquillian Testing with Docker & The Cloud
 

En vedette

Getting Started Building Mobile Applications for iOS and Android
Getting Started Building Mobile Applications for iOS and AndroidGetting Started Building Mobile Applications for iOS and Android
Getting Started Building Mobile Applications for iOS and Android
Embarcadero Technologies
 

En vedette (19)

Getting Started Building Mobile Applications for iOS and Android
Getting Started Building Mobile Applications for iOS and AndroidGetting Started Building Mobile Applications for iOS and Android
Getting Started Building Mobile Applications for iOS and Android
 
Driving Business Applications with Real-Time Data
Driving Business Applications with Real-Time DataDriving Business Applications with Real-Time Data
Driving Business Applications with Real-Time Data
 
KServe Retail Outlet
KServe Retail OutletKServe Retail Outlet
KServe Retail Outlet
 
Infographic: 10 Jaw-dropping Skype for Business Stats
Infographic: 10 Jaw-dropping Skype for Business StatsInfographic: 10 Jaw-dropping Skype for Business Stats
Infographic: 10 Jaw-dropping Skype for Business Stats
 
Managing supplier content and product information
Managing supplier content and product informationManaging supplier content and product information
Managing supplier content and product information
 
2014 Ecommerce Holiday Prep
2014 Ecommerce Holiday Prep2014 Ecommerce Holiday Prep
2014 Ecommerce Holiday Prep
 
How marketers can leverage Ektron DXH's Exact Target for better client engage...
How marketers can leverage Ektron DXH's Exact Target for better client engage...How marketers can leverage Ektron DXH's Exact Target for better client engage...
How marketers can leverage Ektron DXH's Exact Target for better client engage...
 
Arise EMEA - My Story Video Contest
Arise EMEA - My Story Video ContestArise EMEA - My Story Video Contest
Arise EMEA - My Story Video Contest
 
Real time analytics-inthe_cloud
Real time analytics-inthe_cloudReal time analytics-inthe_cloud
Real time analytics-inthe_cloud
 
What's New with vSphere 4
What's New with vSphere 4What's New with vSphere 4
What's New with vSphere 4
 
High Performance Medical Reconstruction Using Stream Programming Paradigms
High Performance Medical Reconstruction Using Stream Programming ParadigmsHigh Performance Medical Reconstruction Using Stream Programming Paradigms
High Performance Medical Reconstruction Using Stream Programming Paradigms
 
InSync Website Portfolio
InSync Website PortfolioInSync Website Portfolio
InSync Website Portfolio
 
Microsoft Office for the iPhone and iPad
Microsoft Office for the iPhone and iPadMicrosoft Office for the iPhone and iPad
Microsoft Office for the iPhone and iPad
 
Innovation management -by Sudhakar Ram
Innovation management -by Sudhakar RamInnovation management -by Sudhakar Ram
Innovation management -by Sudhakar Ram
 
Episode 5 Justin Somaini of Box.com
Episode 5 Justin Somaini of Box.comEpisode 5 Justin Somaini of Box.com
Episode 5 Justin Somaini of Box.com
 
Optimizing the Monetization of a Connected Universe
Optimizing the Monetization of a Connected UniverseOptimizing the Monetization of a Connected Universe
Optimizing the Monetization of a Connected Universe
 
Msp deck v1.0
Msp deck v1.0Msp deck v1.0
Msp deck v1.0
 
iBOS Solution - Incessant Business Operations Suite
iBOS Solution - Incessant Business Operations Suite iBOS Solution - Incessant Business Operations Suite
iBOS Solution - Incessant Business Operations Suite
 
Major project final
Major project  finalMajor project  final
Major project final
 

Similaire à Useful C++ Features You Should be Using

Similaire à Useful C++ Features You Should be Using (20)

Best practices iOS meetup - pmd
Best practices iOS meetup - pmdBest practices iOS meetup - pmd
Best practices iOS meetup - pmd
 
How To Use Scala At Work - Airframe In Action at Arm Treasure Data
How To Use Scala At Work - Airframe In Action at Arm Treasure DataHow To Use Scala At Work - Airframe In Action at Arm Treasure Data
How To Use Scala At Work - Airframe In Action at Arm Treasure Data
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Apache Big Data Europe 2016
Apache Big Data Europe 2016Apache Big Data Europe 2016
Apache Big Data Europe 2016
 
C basics
C basicsC basics
C basics
 
Semplificare l'observability per progetti Serverless
Semplificare l'observability per progetti ServerlessSemplificare l'observability per progetti Serverless
Semplificare l'observability per progetti Serverless
 
How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...How much performance can you get out of Javascript? - Massimiliano Mantione -...
How much performance can you get out of Javascript? - Massimiliano Mantione -...
 
Configure once, run everywhere 2016
Configure once, run everywhere 2016Configure once, run everywhere 2016
Configure once, run everywhere 2016
 
A intro to (hosted) Shiny Apps
A intro to (hosted) Shiny AppsA intro to (hosted) Shiny Apps
A intro to (hosted) Shiny Apps
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Five cool ways the JVM can run Apache Spark faster
Five cool ways the JVM can run Apache Spark fasterFive cool ways the JVM can run Apache Spark faster
Five cool ways the JVM can run Apache Spark faster
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
New and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
New and cool in OSGi R7 - David Bosschaert & Carsten ZiegelerNew and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
New and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
 
Extending js codemotion warsaw 2016
Extending js codemotion warsaw 2016Extending js codemotion warsaw 2016
Extending js codemotion warsaw 2016
 
Embedded C programming session10
Embedded C programming  session10Embedded C programming  session10
Embedded C programming session10
 
C programming session10
C programming  session10C programming  session10
C programming session10
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
IBM Runtimes Performance Observations with Apache Spark
IBM Runtimes Performance Observations with Apache SparkIBM Runtimes Performance Observations with Apache Spark
IBM Runtimes Performance Observations with Apache Spark
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practices
 
20160908 hivemall meetup
20160908 hivemall meetup20160908 hivemall meetup
20160908 hivemall meetup
 

Plus de Embarcadero Technologies

Plus de Embarcadero Technologies (20)

PyTorch for Delphi - Python Data Sciences Libraries.pdf
PyTorch for Delphi - Python Data Sciences Libraries.pdfPyTorch for Delphi - Python Data Sciences Libraries.pdf
PyTorch for Delphi - Python Data Sciences Libraries.pdf
 
Linux GUI Applications on Windows Subsystem for Linux
Linux GUI Applications on Windows Subsystem for LinuxLinux GUI Applications on Windows Subsystem for Linux
Linux GUI Applications on Windows Subsystem for Linux
 
Python on Android with Delphi FMX - The Cross Platform GUI Framework
Python on Android with Delphi FMX - The Cross Platform GUI Framework Python on Android with Delphi FMX - The Cross Platform GUI Framework
Python on Android with Delphi FMX - The Cross Platform GUI Framework
 
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
Introduction to Python GUI development with Delphi for Python - Part 1:   Del...Introduction to Python GUI development with Delphi for Python - Part 1:   Del...
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
 
FMXLinux Introduction - Delphi's FireMonkey for Linux
FMXLinux Introduction - Delphi's FireMonkey for LinuxFMXLinux Introduction - Delphi's FireMonkey for Linux
FMXLinux Introduction - Delphi's FireMonkey for Linux
 
Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2
 
RAD Industrial Automation, Labs, and Instrumentation
RAD Industrial Automation, Labs, and InstrumentationRAD Industrial Automation, Labs, and Instrumentation
RAD Industrial Automation, Labs, and Instrumentation
 
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBaseEmbeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
 
Rad Server Industry Template - Connected Nurses Station - Setup Document
Rad Server Industry Template - Connected Nurses Station - Setup DocumentRad Server Industry Template - Connected Nurses Station - Setup Document
Rad Server Industry Template - Connected Nurses Station - Setup Document
 
TMS Google Mapping Components
TMS Google Mapping ComponentsTMS Google Mapping Components
TMS Google Mapping Components
 
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinar
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinarMove Desktop Apps to the Cloud - RollApp & Embarcadero webinar
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinar
 
Embarcadero RAD server Launch Webinar
Embarcadero RAD server Launch WebinarEmbarcadero RAD server Launch Webinar
Embarcadero RAD server Launch Webinar
 
ER/Studio 2016: Build a Business-Driven Data Architecture
ER/Studio 2016: Build a Business-Driven Data ArchitectureER/Studio 2016: Build a Business-Driven Data Architecture
ER/Studio 2016: Build a Business-Driven Data Architecture
 
The Secrets of SQL Server: Database Worst Practices
The Secrets of SQL Server: Database Worst PracticesThe Secrets of SQL Server: Database Worst Practices
The Secrets of SQL Server: Database Worst Practices
 
Driving Business Value Through Agile Data Assets
Driving Business Value Through Agile Data AssetsDriving Business Value Through Agile Data Assets
Driving Business Value Through Agile Data Assets
 
Troubleshooting Plan Changes with Query Store in SQL Server 2016
Troubleshooting Plan Changes with Query Store in SQL Server 2016Troubleshooting Plan Changes with Query Store in SQL Server 2016
Troubleshooting Plan Changes with Query Store in SQL Server 2016
 
Great Scott! Dealing with New Datatypes
Great Scott! Dealing with New DatatypesGreat Scott! Dealing with New Datatypes
Great Scott! Dealing with New Datatypes
 
Agile, Automated, Aware: How to Model for Success
Agile, Automated, Aware: How to Model for SuccessAgile, Automated, Aware: How to Model for Success
Agile, Automated, Aware: How to Model for Success
 
What's New in DBArtisan and Rapid SQL 2016
What's New in DBArtisan and Rapid SQL 2016What's New in DBArtisan and Rapid SQL 2016
What's New in DBArtisan and Rapid SQL 2016
 
Is This Really a SAN Problem? Understanding the Performance of Your IO Subsy...
Is This Really a SAN Problem? Understanding the Performance of  Your IO Subsy...Is This Really a SAN Problem? Understanding the Performance of  Your IO Subsy...
Is This Really a SAN Problem? Understanding the Performance of Your IO Subsy...
 

Dernier

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 

Dernier (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

Useful C++ Features You Should be Using

  • 1. © 2016 Embarcadero Technologies, Inc. All rights reserved. USEFUL C++ FEATURES YOU SHOULD BE USING David Millington david.millington@embarcadero.com
  • 2. © 2016 Embarcadero Technologies, Inc. All rights reserved. CONTENT • Type inference • Lambdas • New containers • Variadic templates • Smart pointers • And others Not a list of C++11 , nor going into every detail - but showing advantages. Useful even if you already use some of these (eg pre-C++11 smart pointers.)
  • 3. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE Not just auto… but let’s start with it. auto i = 5; // i is an int auto j = foo(); // j is whatever foo() returns
  • 4. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE Not just auto… but let’s start with it. auto i = 5; // i is an int auto j = foo(); // j is whatever foo() returns Decltype too: decltype(i) k; // k is i’s type, an int decltype(i + 5.5f) k; // k is the type of “i + 5.5f”, which is float
  • 5. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE IN A SIMPLE TEMPLATE template<typename A, typename B> void foo(A a, B b) { UNKNOWN m = a * b; // int? float? string? }
  • 6. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE IN A SIMPLE TEMPLATE template<typename A, typename B> void foo(A a, B b) { auto m = a * b; // Solved. }
  • 7. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL STL provides standard iterators making algorithms applicable regardless of the container type – eg std::find over a std::map vs std::unordered_map. Fine for templates – but can you take advantage of this yourself in normal, non-templated code?
  • 8. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL std::map<int, std::wstring> items; for (std::map<int, std::wstring>::const_iterator it = items.begin(); it != items.end(); it++) { }
  • 9. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL std::unordered_map<int, std::wstring> items; for (std::map<int, std::wstring>::const_iterator it = items.begin(); it != items.end(); it++) { } Won’t compile, because despite the interface (begin, end) being the same, the iterator types are different.
  • 10. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL std::unordered_map<int, std::wstring> items; for (std::unordered_map<int, std::wstring>::const_iterator it = items.begin(); it != items.end(); it++) { } What a mess!
  • 11. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL std::map<int, std::wstring> items; for (auto it = items.begin(); it != items.end(); it++) { } std::unordered_map<int, std::wstring> items; Works with either declaration…
  • 12. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL std::unordered_map<int, std::wstring> items; for (auto it : items) { } Works regardless of the type of items Much shorter, clearer, easier to type code
  • 13. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE WHEN USING THE STL for (std::map<int, std::wstring>::const_iterator it = items.begin(); it != items.end(); it++) { } …versus… for (auto it : items) { } Amazing.
  • 14. © 2016 Embarcadero Technologies, Inc. All rights reserved. TYPE INFERENCE Auto: • Reduces typing • Remains strongly (and predictably) typed • Useful when the type isn’t known when writing, but can be deduced at compile time • Allows easy changes • More compact and clear code Investigate decltype too, especially for templates.
  • 15. © 2016 Embarcadero Technologies, Inc. All rights reserved. LAMBDAS std::list<int> items { 1, 2, 3 }; … std::replace_if(items.begin(), items.end(), ???, 99);
  • 16. © 2016 Embarcadero Technologies, Inc. All rights reserved. LAMBDAS struct ItemComparer { private: int m_Value; public: ItemComparer(const int n) : m_Value(n) {}; bool operator()(int i) const { return i % m_Value == 0; } }; std::replace_if(items.begin(), items.end(), ItemComparer(n), 99);
  • 17. © 2016 Embarcadero Technologies, Inc. All rights reserved. LAMBDAS int n = 2; std::replace_if(items.begin(), items.end(), [n](int& i) { return i % n == 0; }, 99);
  • 18. © 2016 Embarcadero Technologies, Inc. All rights reserved. LAMBDAS [] The variable or capture list () The argument list {} Code Making the simplest lambda [](){} a method that captures nothing, is passed no arguments, and does nothing. [n](int& i) { return i % n == 0; }
  • 19. © 2016 Embarcadero Technologies, Inc. All rights reserved. LAMBDAS auto f = [this, n, &j](int& i) { return i % n == 0; }; • Neat and readable • Inline in code • Inlineable and performant • Capture variables by value or reference • Behave like an object
  • 20. © 2016 Embarcadero Technologies, Inc. All rights reserved. VARIADIC TEMPLATES template<typename T> T mult(T first) { return first; } template<typename T, typename... Others> T mult(T first, Others... others) { return first * mult(others...); } int z = mult(1, 2, 3, 4); // z = 24 * Based on http://eli.thegreenplace.net/2014/variadic-templates-in-c/
  • 21. © 2016 Embarcadero Technologies, Inc. All rights reserved. VARIADIC TEMPLATES std::tuple<int, float, std::string> t { 1, 2.5, "hello"}; float v = std::get<1>(t);
  • 22. © 2016 Embarcadero Technologies, Inc. All rights reserved. SMART POINTERS No: Foo* foo = new Foo(); __try { // } __finally { delete foo; } Yes (sortof): { scoped_ptr<Foo> foo = new Foo(); } ^- foo is freed
  • 23. © 2016 Embarcadero Technologies, Inc. All rights reserved. SMART POINTERS Using boost or C++11: { shared_ptr<Foo> foo = new Foo(); bar->myfoo = foo; // bar::myfoo is a shared_ptr<Foo> } // <- foo is not freed, a reference is still held
  • 24. © 2016 Embarcadero Technologies, Inc. All rights reserved. SMART POINTERS Using boost? Move to shared_ptr (very familiar!) and unique_ptr instead of scoped_ptr In general, already using them or not: • Use unique_ptr where possible • Use shared_ptr not out of ease but when you want to share • Don’t expect automatic threadsafety apart from +/- refcount • Use shared_ptr<Foo> p = make_shared<Foo>; and make_unique<T> if available - http://stackoverflow.com/questions/17902405/how-to-implement-make- unique-function-in-c11 • Never write new or delete
  • 25. © 2016 Embarcadero Technologies, Inc. All rights reserved. CONTAINERS hash_map – common, but never standardised! Use unordered_set, unordered_map, unordered_multiset, unordered_multimap.
  • 26. © 2016 Embarcadero Technologies, Inc. All rights reserved. ATOMIC PRIMITIVES C++11 defines a memory model – so race conditions and odd threading behaviour no longer undefined behaviour. Low-level primitives in <atomic> Generally stick to things like mutex.
  • 27. © 2016 Embarcadero Technologies, Inc. All rights reserved. STATIC ASSERTIONS In the past, clever code & macros to get something like: STATIC_ASSERT(x); Now, static_assert(sizeof(float) == 4, "float has unexpected size");
  • 28. © 2016 Embarcadero Technologies, Inc. All rights reserved. C++BUILDER • FireMonkey – cross-platform UI, native controls, multi-device specialization • Similar for other frameworks – database, REST, enterprise, RAD Server…
  • 29. © 2016 Embarcadero Technologies, Inc. All rights reserved. C++BUILDER Compilers: • Classic BCC32 • New Clang-enhanced Resources: • Docwiki lists C++11 features in ‘old’ classic compiler • And language support in new Clang compiler (including newer than C++11 features)
  • 30. © 2016 Embarcadero Technologies, Inc. All rights reserved. USEFUL FEATURES Code clarity • Auto – clearer, easier • Lambdas – inline, readable, function content visible where it’s used Safety • Smart pointers – use unique_ptr where possible • Static assertions Misc • Standardised unordered containers • Standardised memory model – defined (even if unexpected) behaviour C++Builder • Cross-platform support • UI – specializable for different platforms and devices. Yet you can use native controls too. • New compilers – Clang-based, plus our extensions. Better language support, better performance. Free compiler available!
  • 31. © 2016 Embarcadero Technologies, Inc. All rights reserved. USEFUL FEATURES Code clarity • Auto – clearer, easier • Lambdas – inline, readable, function content visible where it’s used Safety • Smart pointers – use unique_ptr where possible • Static assertions Misc • Standardised unordered containers • Standardised memory model – defined (even if unexpected) behaviour C++Builder • Cross-platform support • UI – specializable for different platforms and devices. Yet you can use native controls too. • New compilers – Clang-based, plus our extensions. Better language support, better performance. Free compiler available!
  • 32. © 2016 Embarcadero Technologies, Inc. All rights reserved. USEFUL FEATURES Code clarity • Auto – clearer, easier • Lambdas – inline, readable, function content visible where it’s used Safety • Smart pointers – use unique_ptr where possible • Static assertions Misc • Standardised unordered containers • Standardised memory model – defined (even if unexpected) behaviour C++Builder • Cross-platform support • UI – specializable for different platforms and devices. Yet you can use native controls too. • New compilers – Clang-based, plus our extensions. Better language support, better performance. Free compiler available!
  • 33. © 2016 Embarcadero Technologies, Inc. All rights reserved. USEFUL FEATURES Code clarity • Auto – clearer, easier • Lambdas – inline, readable, function content visible where it’s used Safety • Smart pointers – use unique_ptr where possible • Static assertions Misc • Standardised unordered containers • Standardised memory model – defined (even if unexpected) behaviour C++Builder • Cross-platform support • UI – specializable for different platforms and devices. Yet you can use native controls too. • New compilers – Clang-based, plus our extensions. Better language support, better performance. Free compiler available!
  • 34. © 2016 Embarcadero Technologies, Inc. All rights reserved. USEFUL FEATURES Code clarity • Auto – clearer, easier • Lambdas – inline, readable, function content visible where it’s used Safety • Smart pointers – use unique_ptr where possible • Static assertions Misc • Standardised unordered containers • Standardised memory model – defined (even if unexpected) behaviour C++Builder • Cross-platform support • UI – specializable for different platforms and devices. Yet you can use native controls too. • New compilers – Clang-based, plus our extensions. Better language support, better performance. Free compiler available!
  • 35. © 2016 Embarcadero Technologies, Inc. All rights reserved. RESOURCES • Auto • http://thbecker.net/articles/auto_and_decltype/section_01.html • Lambdas • http://www.drdobbs.com/cpp/lambdas-in-c11/240168241 • Smart pointers • http://www.acodersjourney.com/2016/05/top-10-dumb-mistakes-avoid-c-11-smart-pointers/ • Variadic templates • http://eli.thegreenplace.net/2014/variadic-templates-in-c/ • https://www.murrayc.com/permalink/2015/12/05/modern-c-variadic-template-parameters-and-tuples/ • Static assertions • http://stackoverflow.com/questions/1647895/what-does-static-assert-do-and-what-would-you-use-it-for • C++ Builder • https://www.embarcadero.com/products/cbuilder • https://www.embarcadero.com/free-tools/ccompiler • http://docwiki.embarcadero.com/RADStudio/Berlin/en/C++11_Language_Features_Compliance_Status • http://docwiki.embarcadero.com/RADStudio/Berlin/en/C%2B%2B11_Features_Supported_by_RAD_Studio _Clang-enhanced_C%2B%2B_Compilers