SlideShare a Scribd company logo
C++
IDIOMS
JANANI A
26 SEP 2013
Topics Covered
▪ Introduction
▪ RAII
▪ Attorney client
▪ Virtual friend functions
▪ Base from member
▪ Address of
▪ PIMPL
▪ COW
▪ SFINAE and Type Traits
▪ Tag dispatching
Introduction
Workarounds for limitations with the basic uses of the language.
RAII (Resource Acquisition Is Initialization)
▪ A fundamental programming idiom used
to automate resource management.
RAII
▪ Resources are acquired during initialization, when there is no
chance of them being used before they are available, and
released with the destruction of the same objects, which is
guaranteed to take place even in case of errors.
Typical uses :
▪ Obtaining memory from new, malloc, IMalloc::Alloc, etc. Which
must be matched with a call to delete, free, IMalloc::Free, etc.
▪ Opening a file, which must be closed.
▪ Synchronization primitives like monitors, critical sections, etc.
Which must be released to allow other threads to obtain them.
▪ Opening a network connection, database connection, Creating
a Windows GDI object, Opening a Registry handle, etc.
▪ Example : STL’s std::auto_ptr
Attorney-Client - The limitation
▪ Control the granularity of access to the implementation
details of a class.
▪ Friends in C++ is an all-or-nothing proposition.
A friend declaration in C++ gives complete access to the
internals of a class.
class Foo
{
private:
void A(int a);
void B(float b);
void C(double c);
friend class Bar;
};
class Bar
{
// This class needs access to Foo::A and Foo::B only.
// C++ friendship rules, however, give access to all the private members
of Foo.
};
Attorney-Client - The workaround
class Attorney;
class Client
{
private:
void A(int a);
void B(float b);
void C(double c);
friend class Attorney;
};
class Attorney
{
private:
Client c;
static void callA(int a) { c.A(a); }
static void callB(float b) { c.B(b); }
friend class Bar;
};
class Bar
{// Bar now has access to only Client::A and Client::B
through the Attorney.
};
Virtual friend functions
▪ Simulate a virtual friend function.
class Base
{
public:
friend ostream& operator << (ostream& o, const Base& b);
// ...
protected:
virtual void print(ostream& o) const
{ ... }
};
inline std::ostream& operator<< (std::ostream& o, const Base& b)
{
b.print(o); // delegate the work to a polymorphic member
function.
return o;
}
class Derived : public Base
{
protected:
virtual void print(ostream& o) const
{ ... }
};
Base from member
▪ To initialize a base class from a data-member of the
derived class.
▪ Data member cannot be initialized before initializing the
base class.
▪ Ron Klatchko and Dietmar Kühl developed a way around.
▪ Base classes are initialized in the order they are declared.
Base from member - The limitation
namespace std {
class streambuf;
class ostream {
explicit ostream(std::streambuf * buf);
//...
};
}
class fdoutbuf // A customization of streambuf
: public std::streambuf
{
public:
explicit fdoutbuf( int fd );
//...
};
class fdostream
: public std::ostream
{
protected:
fdoutbuf buf;
public:
explicit fdostream( int fd )
: buf( fd ), std::ostream( &buf )
// This is not allowed: buf can't be initialized before std::ostream.
// std::ostream needs a std::streambuf object defined inside fdoutbuf.
{}
};
Base from member - The workaround
class fdoutbuf_pbase // A newly introduced class
{
public:
fdoutbuf sbuffer; // The member moved 'up' the hierarchy.
explicit fdoutbuf_pbase(int fd) : sbuffer(fd)
{}
};
class fdostream : protected virtual fdoutbuf_pbase
, public std::ostream
{
public:
explicit fdostream(int fd) : fdoutbuf_pbase(fd), //
Initialize the newly added base before std::ostream.
std::ostream(&sbuffer) // Now safe to pass the pointer
{}
//...
};
Address of - The limitation
▪ Find address of an object of a class that has an
overloaded unary ampersand (&) operator.
▪ This function is already in the <memory> header of the
new C++ standard C++11.
Address of
PIMPL (Private Implementation)
▪ Described by Herb Sutter.
▪ To hide the implementation details of an interface from
ordinary clients.
▪ Technique to minimize coupling via the separation of
interface and implementation.
▪ Also known as Bridge pattern, Cheshire Cat, Handle/
Body.class Add
{
int x;
int y;
public:
Add() { }
int add();
};
#include “AddDetails.h"
#include " Add.h"
Add ::Add()
{
ptr = new AddDetails();
}
Add::~ Add()
{
delete ptr;
}
int Add::add()
{
return ptr -> add();
}
Add.cpp
class AddDetails;
class Add
{
AddDetails* ptr;
public:
Add();
~Add();
int add();
};
Add.h
#include " AddDetails.h";
int AddDetails::add()
{
return x+y;
}
AddDetails.cpp
class AddDetails
{
int x;
int y;
public:
AddDetails() { }
int add();
};
AddDetails.h
#include “Add.h"
int _tmain(int argc, _TCHAR* argv[])
{
Add obj;
int result = obj.add();
return 0;
}
Main.cpp
PIMPL
COW (Copy On Write)
▪ Copying an object can sometimes cause a performance
penalty.
▪ Achieve lazy copy optimization, do the work just when you
need because of efficiency.
▪ If objects are frequently copied but infrequently modified
later.
template <class T>
class CowPtr
{
public:
typedef boost::shared_ptr<T> RefPtr;
private:
RefPtr m_sp;
void detach()
{
T* tmp = m_sp.get();
if( !( tmp == 0 || m_sp.unique() ) ) {
m_sp = RefPtr( new T( *tmp ) );
}
}
public:
COW (Copy On Write)
CowPtr(T* t) : m_sp(t){}
CowPtr(const RefPtr& refptr) : m_sp(refptr) {}
CowPtr(const CowPtr& cowptr) : m_sp(cowptr.m_sp) {}
CowPtr& operator=(const CowPtr& rhs)
{
m_sp = rhs.m_sp; // no need to check for self-assignment with boost::shared_ptr
return *this;
}
const T& operator*() const
{
return *m_sp;
}
T& operator*()
{
detach();
return *m_sp;
}
const T* operator->() const
{
return m_sp.operator->();
}
T* operator->()
{
detach();
return m_sp.operator->();
}
};
COW (Copy On Write)
char & String::operator[](int)
CowPtr<String> s1 = "Hello";
char &c = s1->operator[](4); // Non-const detachment does
nothing here
CowPtr<String> s2(s1); // Lazy-copy, shared state
c = '!'; // Uh-oh
SFINAE (Substitution Failure Is Not An Error)
▪ David Vandevoorde first introduced the acronym SFINAE.
▪ It allows a template to determine certain properties of its
template arguments at instantiation time.
▪ Many developers found the behavior useful for compile-
time introspection.
int negate(int& i) { return -i; }
template <class F>
typename F::result_type negate(const F& f) { return -f(); }
negate(1);
▪ Type Traits are classes to obtain type information on
compile-time.
SFINAE
#include <type_traits>
#include <iostream>
template<class T> // foo1 overloads are enabled via the return type
typename std::enable_if<std::is_floating_point<T>::value, T>::type
foo1(T t)
{
std::cout << "foo1: floatn"; return t;
}
//Using helper type
template<class T> std::enable_if_t<std::is_integral<T>::value, T> foo1(T t)
{
std::cout << "foo1: intn"; return t;
}
template<class T>// foo2 overload is enabled via a parameter
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* =0)
{
return t;
}
template<class T , // foo3 overload is enabled via a template parameter
class = typename std::enable_if<std::is_integral<T>::value>::type >
T foo3(T t) // note, function signature is unmodified
{
return t;
}
int main()
{
foo1(1.2); // OK, calls the first version of foo1()
foo1(10); // OK, calls the second version of foo1()
// foo2(0.1); // compile-time error
foo2(7); // OK
// foo3(1.2); // compile-time error
foo3(34); // OK
}
SFINAE
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T>
{ typedef T type; };
Tag Dispatching
▪ Tag dispatching is a technique for compile time
dispatching between a few overloaded functions by using
the properties of a type.
void work_fast(int i) { /*fast implementation*/ }
void work_fast(long l) { /*fast implementation*/ }
void work_slow(float f) { /*slow implementation*/ }
void work_slow(double d) { /*slow implementation*/ }
int main ()
{
int w; long x;
float y; double z;
work_fast(w); work_fast(x);
work_slow(y); work_slow(z);
return 0;
}
Tag Dispatching
▪ Tag dispatching is a technique for compile time
dispatching between a few overloaded functions by using
the properties of a type.
struct fast_speed_tag {};
struct slow_speed_tag {};
template <typename T>
void work_dispatch (const T &val, const slow_speed_tag&)
{
std::cout << "slow" << std::endl;
}
template <typename T>
void work_dispatch (const T &val, const fast_speed_tag&)
{
std::cout << "fast" << std::endl;
}
template <typename T>
struct traits // default
{
typedef slow_speed_tag speed;
};
template <>
struct traits<int> { // we would do the same for long etc
typedef fast_speed_tag speed;
};
template <typename T>
void work (const T &val)
{
work_dispatch(val, typename traits<T>::speed());
}
int main ()
{
int x;
float y;
work(x); // fast
work(y); // slow
return 0;
}
Tag Dispatching
▪ One of the best examples of the Tag dispatch technique is
the implementation of std::advance() within STL iterators.
▪ The tag types are empty structs that are never used. As
such, the compiler will usually be able to optimize and
make them totally disappear from the compiled code –
which makes this technique even more appealing.
Tag Dispatching
▪ 94 Idioms at,
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms
References
QUESTIONS
THANK YOU

More Related Content

What's hot

C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
CyberPlusIndia
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
corehard_by
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Kim Hunmin
 
Clang tidy
Clang tidyClang tidy
Clang tidy
Yury Yafimachau
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
Bartlomiej Filipek
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
Hacking parse.y (RubyConf 2009)
Hacking parse.y (RubyConf 2009)Hacking parse.y (RubyConf 2009)
Hacking parse.y (RubyConf 2009)
ujihisa
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
Sergey Platonov
 
CODEsign 2015
CODEsign 2015CODEsign 2015
CODEsign 2015
Max Kleiner
 
Rcpp11
Rcpp11Rcpp11
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
Thomas Pollak
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
julien pauli
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
Kamil Witecki
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 ProcessShu-Yu Fu
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
Stefan
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
 
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 AttributesEmpty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes
Bartlomiej Filipek
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
Jen Yee Hong
 

What's hot (20)

C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Hacking parse.y (RubyConf 2009)
Hacking parse.y (RubyConf 2009)Hacking parse.y (RubyConf 2009)
Hacking parse.y (RubyConf 2009)
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
 
CODEsign 2015
CODEsign 2015CODEsign 2015
CODEsign 2015
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
 
C++ references
C++ referencesC++ references
C++ references
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
 
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 AttributesEmpty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes
Empty Base Class Optimisation, [[no_unique_address]] and other C++20 Attributes
 
2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english2018 cosup-delete unused python code safely - english
2018 cosup-delete unused python code safely - english
 

Similar to C++ idioms.pptx

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
Muhammed Thanveer M
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guide
Tiago Faller
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
report
reportreport
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
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
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
Sasha Goldshtein
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
LogeekNightUkraine
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
C++ language
C++ languageC++ language
C++ language
Elizabeth Pisarek
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
TamiratDejene1
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
corehard_by
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
Ramesh Nair
 

Similar to C++ idioms.pptx (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guide
 
Day 1
Day 1Day 1
Day 1
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
report
reportreport
report
 
C++ theory
C++ theoryC++ theory
C++ theory
 
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
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
C++ language
C++ languageC++ language
C++ language
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
Lecture5
Lecture5Lecture5
Lecture5
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 

Recently uploaded

Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 

C++ idioms.pptx

  • 2. Topics Covered ▪ Introduction ▪ RAII ▪ Attorney client ▪ Virtual friend functions ▪ Base from member ▪ Address of ▪ PIMPL ▪ COW ▪ SFINAE and Type Traits ▪ Tag dispatching
  • 3. Introduction Workarounds for limitations with the basic uses of the language.
  • 4. RAII (Resource Acquisition Is Initialization) ▪ A fundamental programming idiom used to automate resource management.
  • 5. RAII ▪ Resources are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, which is guaranteed to take place even in case of errors. Typical uses : ▪ Obtaining memory from new, malloc, IMalloc::Alloc, etc. Which must be matched with a call to delete, free, IMalloc::Free, etc. ▪ Opening a file, which must be closed. ▪ Synchronization primitives like monitors, critical sections, etc. Which must be released to allow other threads to obtain them. ▪ Opening a network connection, database connection, Creating a Windows GDI object, Opening a Registry handle, etc. ▪ Example : STL’s std::auto_ptr
  • 6. Attorney-Client - The limitation ▪ Control the granularity of access to the implementation details of a class. ▪ Friends in C++ is an all-or-nothing proposition. A friend declaration in C++ gives complete access to the internals of a class. class Foo { private: void A(int a); void B(float b); void C(double c); friend class Bar; }; class Bar { // This class needs access to Foo::A and Foo::B only. // C++ friendship rules, however, give access to all the private members of Foo. };
  • 7. Attorney-Client - The workaround class Attorney; class Client { private: void A(int a); void B(float b); void C(double c); friend class Attorney; }; class Attorney { private: Client c; static void callA(int a) { c.A(a); } static void callB(float b) { c.B(b); } friend class Bar; }; class Bar {// Bar now has access to only Client::A and Client::B through the Attorney. };
  • 8. Virtual friend functions ▪ Simulate a virtual friend function. class Base { public: friend ostream& operator << (ostream& o, const Base& b); // ... protected: virtual void print(ostream& o) const { ... } }; inline std::ostream& operator<< (std::ostream& o, const Base& b) { b.print(o); // delegate the work to a polymorphic member function. return o; } class Derived : public Base { protected: virtual void print(ostream& o) const { ... } };
  • 9. Base from member ▪ To initialize a base class from a data-member of the derived class. ▪ Data member cannot be initialized before initializing the base class. ▪ Ron Klatchko and Dietmar Kühl developed a way around. ▪ Base classes are initialized in the order they are declared.
  • 10. Base from member - The limitation namespace std { class streambuf; class ostream { explicit ostream(std::streambuf * buf); //... }; } class fdoutbuf // A customization of streambuf : public std::streambuf { public: explicit fdoutbuf( int fd ); //... }; class fdostream : public std::ostream { protected: fdoutbuf buf; public: explicit fdostream( int fd ) : buf( fd ), std::ostream( &buf ) // This is not allowed: buf can't be initialized before std::ostream. // std::ostream needs a std::streambuf object defined inside fdoutbuf. {} };
  • 11. Base from member - The workaround class fdoutbuf_pbase // A newly introduced class { public: fdoutbuf sbuffer; // The member moved 'up' the hierarchy. explicit fdoutbuf_pbase(int fd) : sbuffer(fd) {} }; class fdostream : protected virtual fdoutbuf_pbase , public std::ostream { public: explicit fdostream(int fd) : fdoutbuf_pbase(fd), // Initialize the newly added base before std::ostream. std::ostream(&sbuffer) // Now safe to pass the pointer {} //... };
  • 12. Address of - The limitation ▪ Find address of an object of a class that has an overloaded unary ampersand (&) operator. ▪ This function is already in the <memory> header of the new C++ standard C++11.
  • 14. PIMPL (Private Implementation) ▪ Described by Herb Sutter. ▪ To hide the implementation details of an interface from ordinary clients. ▪ Technique to minimize coupling via the separation of interface and implementation. ▪ Also known as Bridge pattern, Cheshire Cat, Handle/ Body.class Add { int x; int y; public: Add() { } int add(); };
  • 15. #include “AddDetails.h" #include " Add.h" Add ::Add() { ptr = new AddDetails(); } Add::~ Add() { delete ptr; } int Add::add() { return ptr -> add(); } Add.cpp class AddDetails; class Add { AddDetails* ptr; public: Add(); ~Add(); int add(); }; Add.h #include " AddDetails.h"; int AddDetails::add() { return x+y; } AddDetails.cpp class AddDetails { int x; int y; public: AddDetails() { } int add(); }; AddDetails.h #include “Add.h" int _tmain(int argc, _TCHAR* argv[]) { Add obj; int result = obj.add(); return 0; } Main.cpp PIMPL
  • 16. COW (Copy On Write) ▪ Copying an object can sometimes cause a performance penalty. ▪ Achieve lazy copy optimization, do the work just when you need because of efficiency. ▪ If objects are frequently copied but infrequently modified later. template <class T> class CowPtr { public: typedef boost::shared_ptr<T> RefPtr; private: RefPtr m_sp; void detach() { T* tmp = m_sp.get(); if( !( tmp == 0 || m_sp.unique() ) ) { m_sp = RefPtr( new T( *tmp ) ); } } public:
  • 17. COW (Copy On Write) CowPtr(T* t) : m_sp(t){} CowPtr(const RefPtr& refptr) : m_sp(refptr) {} CowPtr(const CowPtr& cowptr) : m_sp(cowptr.m_sp) {} CowPtr& operator=(const CowPtr& rhs) { m_sp = rhs.m_sp; // no need to check for self-assignment with boost::shared_ptr return *this; } const T& operator*() const { return *m_sp; } T& operator*() { detach(); return *m_sp; } const T* operator->() const { return m_sp.operator->(); } T* operator->() { detach(); return m_sp.operator->(); } };
  • 18. COW (Copy On Write) char & String::operator[](int) CowPtr<String> s1 = "Hello"; char &c = s1->operator[](4); // Non-const detachment does nothing here CowPtr<String> s2(s1); // Lazy-copy, shared state c = '!'; // Uh-oh
  • 19. SFINAE (Substitution Failure Is Not An Error) ▪ David Vandevoorde first introduced the acronym SFINAE. ▪ It allows a template to determine certain properties of its template arguments at instantiation time. ▪ Many developers found the behavior useful for compile- time introspection. int negate(int& i) { return -i; } template <class F> typename F::result_type negate(const F& f) { return -f(); } negate(1); ▪ Type Traits are classes to obtain type information on compile-time.
  • 20. SFINAE #include <type_traits> #include <iostream> template<class T> // foo1 overloads are enabled via the return type typename std::enable_if<std::is_floating_point<T>::value, T>::type foo1(T t) { std::cout << "foo1: floatn"; return t; } //Using helper type template<class T> std::enable_if_t<std::is_integral<T>::value, T> foo1(T t) { std::cout << "foo1: intn"; return t; } template<class T>// foo2 overload is enabled via a parameter T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* =0) { return t; } template<class T , // foo3 overload is enabled via a template parameter class = typename std::enable_if<std::is_integral<T>::value>::type > T foo3(T t) // note, function signature is unmodified { return t; }
  • 21. int main() { foo1(1.2); // OK, calls the first version of foo1() foo1(10); // OK, calls the second version of foo1() // foo2(0.1); // compile-time error foo2(7); // OK // foo3(1.2); // compile-time error foo3(34); // OK } SFINAE template<bool B, class T = void> struct enable_if {}; template<class T> struct enable_if<true, T> { typedef T type; };
  • 22. Tag Dispatching ▪ Tag dispatching is a technique for compile time dispatching between a few overloaded functions by using the properties of a type. void work_fast(int i) { /*fast implementation*/ } void work_fast(long l) { /*fast implementation*/ } void work_slow(float f) { /*slow implementation*/ } void work_slow(double d) { /*slow implementation*/ } int main () { int w; long x; float y; double z; work_fast(w); work_fast(x); work_slow(y); work_slow(z); return 0; }
  • 23. Tag Dispatching ▪ Tag dispatching is a technique for compile time dispatching between a few overloaded functions by using the properties of a type. struct fast_speed_tag {}; struct slow_speed_tag {}; template <typename T> void work_dispatch (const T &val, const slow_speed_tag&) { std::cout << "slow" << std::endl; } template <typename T> void work_dispatch (const T &val, const fast_speed_tag&) { std::cout << "fast" << std::endl; }
  • 24. template <typename T> struct traits // default { typedef slow_speed_tag speed; }; template <> struct traits<int> { // we would do the same for long etc typedef fast_speed_tag speed; }; template <typename T> void work (const T &val) { work_dispatch(val, typename traits<T>::speed()); } int main () { int x; float y; work(x); // fast work(y); // slow return 0; } Tag Dispatching
  • 25. ▪ One of the best examples of the Tag dispatch technique is the implementation of std::advance() within STL iterators. ▪ The tag types are empty structs that are never used. As such, the compiler will usually be able to optimize and make them totally disappear from the compiled code – which makes this technique even more appealing. Tag Dispatching
  • 26. ▪ 94 Idioms at, http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms References