SlideShare a Scribd company logo
1 of 28
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++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 Doumlercorehard_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
 
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++17Bartlomiej 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
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machinejulien pauli
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil 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 ToolboxStefan
 
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 AutumnMoriyoshi 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 AttributesBartlomiej 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 - englishJen 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

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 MelayiMuhammed Thanveer M
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
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 guideTiago 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 stroustrupSyedHaroonShah4
 
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-13Abu Saleh
 
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.17LogeekNightUkraine
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdfTamiratDejene1
 
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 DartRamesh 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

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...kellynguyen01
 
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...ICS
 
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-...Steffen Staab
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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 WorkerThousandEyes
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
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 ...MyIntelliSource, Inc.
 
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.pdfkalichargn70th171
 
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...panagenda
 
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...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
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.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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 PrecisionSolGuruz
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Recently uploaded (20)

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...
 
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...
 
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-...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
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 ...
 
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...
 
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
 
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...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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