Modern C++ Design Patterns and Idioms With New Features
Modern C++ Design Patterns and Idioms With New Features
ABSTRACT
The object oriented paradigm plays a vital role not only in programming languages but also in the field of
database, operating system and other field of computer science. This paper defines the overview of the
concept of Design Patterns, Idioms and functional programming and defines how these concepts are
implemented in C++.It describes how New features in C++ change the way of the programming, and
integrate the new algorithms, libraries and the way to program in Object Oriented fashion in C++.We
illustrate how much efficient and effective programming practices are been done through these concepts in
the industry. We have briefly discuss the major and prime new features, libraries, algorithms added to C++11
and improved in C++14.
Keywords: Design Pattern, Idioms, Modern Features, pointers and functional Programming
context and may not be applicable or maybe even
1. Introduction
actively harmful if used outside that context, For
Design patterns and idioms are important concepts example a pattern used to solve problems with wear
helping programmers to produce good code and avoid application may not will be suitable for real-time
pitfalls.So what is a design pattern? Design pattern is applications. Patterns are designed to present best
commonly defined as being tested solution to a practices in a practical way building on the knowledge
recurring problem in a particular context.so let's take of experienced developers, there's a saying patterns
this apart see what it implies toqualify as a design are discovered not invented, if something really is a
pattern, a solution has to be tested and it's pros and best practice you'd expect experienced practitioners
cons well understood, design patterns document to discover independently because it is the best way
solutions that have been discovered and refine over to do the job in fact the patterns are best practices
time by experienced programmers. It always seems a you may have well discovered something by yourself
little strange to see design patterns describe the and it is quite common for a good developer to get a
technologies that are only a few months old so cant slight feeling of anticlimax when hearing about the
have test that much. Secondly the problem solved by patterns.
pattern should be widely applicable, it isn't really
Design patterns have several advantages for the
worth taking trouble to document the solution to a
developer, first they provide shared language that
problem if it isn't likely to recur or if no one else is
102
communicate insight and experience about problems consisting of those that are class based and those that
and how they can be solved for instance when are object based and here we can see the 23 divided
someone says that use the visitor is a concise way of into their groupas shown in fig.
saying that they want to add functionality to a class
Let's briefly reviews some common patterns, first one
without changing it, separating the operation from
we discuss is Model View Controllerbetter known as
the class been operated on and of course using design
MVC, this was perhaps the original design pattern it
patterns helps you build on the experience of others
was discovered byTrygveReenskaug, when he was a
not onlydoes this help you to avoid problems and
visiting science conference in the smalltalkRupert
pitfalls that may not be obvious, but it also guards
XeroxPalo Alto research Lab and he published the first
against reinventing the wheel thinking up your own
paper on his in 1978, [1] the idea behind MVC is to
solution to a problem where a perfectly good one
decouple a model which Reenskaug originally
already exist.[4,5]A good programmer is humble
described as knowledge from the way in which it is
recognising that he or she doesn't necessarily know
viewed. Controllers provided interface between the
everything that's a home-grown solution is unlikely to
user and the rest of the system MVC was discovered
match established best practice
at the very birth of Graphical User Interfaces and is
2. Literature Review now the basis for countless applications and
frameworks in both desktop and web world's there
Where did design patterns originate? An architect
are many variations on MVCs such as Model View
called Christopher Alexander discovered patterns in
Presenterand Model View Viewmodel all of which built
architectural designs and he published book called A
with the basic idea separating a model from its
Pattern language towns buildings construction in the
representation so model holds and manipulate data
1970s, this defined 253 patterns that formed what he
which is displayed by one or more views controllers
called a pattern language,[7] Kent Beck and Ward
pass interaction information to the model and the
Cunningham began studying patterns and software in
user interacts with controllers and views.
the early 1980sErich Gamma became intrusted while
doing his PhD. Gamma Richard Helm began
cataloguing patterns in 1991,they were joined by
Ralph Johnson and John Vlissidesand they all became
known as the gang of four their work was published
as a book design patterns elements of reusable object
oriented software, this now universally known as
gand of four book and describe 23 basic patterns.[13]
Figure 2:
the code. It can be done by using only destructor but has number of uses one of which is improving
if the exception is thrown the mutex may not be compilation speed since the compiler doesn't have to
unlocked, so we can use a simple class that uses RAII recompile when implementation details changed as
to unlock the mutex after its been used, which will long as the class interface remains the same. Typically
even work correctly if exception gets thrown, particle implementation is placed in a separate class with the
example given below. All of this should work in any main interface class attaining only a pointer to the
development environment that supports C++ 11 or implementing class
14.
classPim {
Class Lock { PimImp *Pi;
lock () { // Do something here } //
~lock() { //Undo here } };
}; classPimImp {};
provides a way to hide implementation details of a The Singleton Pattern comes under that classification
class so that the implementations details and of Creational Pattern, which deals with the best ways
dependencies don't pollute the class interface. This to create objects. These are used where only one
Page
instance of an object is needed throughout the d. R values: The area of Rvalues has perhaps a
lifetime of an application. The Singleton class is greatest effect on how the developer write in C++.
instantiated at the time of first access and same Particularly who are writing the libraries? C++ now let
instance is used thereafter till the application quits. you take a reference to a temporaryRvalue which
hasnt been previously possible. Function overloading
class Singleton
let you distinguished between normal and Rvalue
{
references and this is very useful because if you know
private:
you are dealing with the temporary you can steal its
static Singleton* instance;
state rather than have to copy it, this is called Move
public:
semantics. And has hugely increase the efficiency of
static Singleton* getInstance();
code and standard library.
};
e. Explicit Keyword: The explicit keyword can now
5. Modern Features in C++ be applied to conversion operators as well as
constructors and that helps avoid unexpected
Let briefly discuss the version of C++, then see what
conversions.
they added to the language. Although C++ is been
f. Inference: Type inference is now supported
around for about some time, the first release was in
through the alter keyword, we also have decltype
1998, this defined why we called this thing as
which deduces the type of the variable or expression,
traditional C++,[6] which included classes and
which can be used to declare a variable that for
templates. In 2003 a minor update, mostly
example may has same type as x*y, this is particularly
considering the bug fixes, and this was followed by
useful in template code, when the types are only
the major development program, which took 8 years
known at the compile time.
and added a large number of significant new features
g. Lamdas: Lamdas or anonymous functions are
to the language, we will be looking at these and how
particularly useful addition to C++.not only the made
they affect the way we write code. Now the standard
code more concisely which is easy to understand but
committee set schedule for release every 3 years,
they are are also necessary if one is going to program
thats why we saw the release of C++ 14, this mainly
in the functional style.
provided the bug fixes and improvements. So 3 year
h. Range For: Range for is relatively simple addition
release cycle which means we see the new release in
providing a high level way to iterate over collection of
2017.
all types, this idea is supported by many languages, it
Lets run through the new features thats were is also possible to write custom classes that will work
introduced by the C++ 11 standard, we see that they for the range for, which make code more useable and
have significantly updated the language. maintainable because you no longer have to wonder
a. Constructors: Two changes were made the way in just how you going to iterate over custom collection.
whichobjects are constructed, delegating constructor i. Nullptr: C++ now has a value to represent Null
like one constructor call another, while inheriting pointer. This is nullptr which is the proper pointer of
constructor let the derived class initialize itself using type null pointer T. prior to this developers had to use
constructors form the base class. Both these can help either the null macro inherited from c, which is
reduce code duplication. implementation dependence in assassinating
b. Members: Two keywords have been added to including header files or zero, which make null pointer
control how class members functions are handled. an int, that can cause problems
The default keywords tell the compiler to generate j. Constexpr: constexpr keyword provides support
the default implementations, such as default copy for generalized constant expressions, which means
constructors. The Delete keyword tells the compiler computation at runtime rather than compile time.
not to generate the default version and now provide k. Static_assert: static assertion is the one that is
the more efficient and better documented way to checked at the compile time, rather than runtime, this
inhibit the default creation and copy. can be used to get away with type traits which
c. Initialization: There are major changes in the area enables the compilers to check property of types.
of initialization, Uniform initialization means just These are especially useful when using templates as
about any data structure can be initialization using they give the developer a control over the types used
the same syntax. For example a vector can be to extensiate the templates.
initialized as the same way as array. This also apply to l. Templates: there are two main changes in this
area, veriadic templates are perhaps the most
106
variable numbers of arguments. Templates aliases Object oriented is not good at composing
which not only allow to provide aliases for template algorithms.
types but more usefully to provide aliases with Object oriented data structure is often slow.
parameters types already bound. Object oriented does not handle concurrency.
6. New Libraries Features: Principal of function programming:
Number of new features have been added to 7.1 Higher order Function
standard libraries as well. Function as a data, so functions are consider to be
a. Containers: A number of new containers including object and passed around and operated on, they can
hashtables, tuples, singly-linked lists and fixed arrays, pass the function as arguments and used them as a
that last one is interesting because it a refer for built- result value. Function that operates on other function
in array that allows the arrays to support all the is called higher order functions. Function is used as
standard containers operations. building blocks and simple function composed of
b. Algorithms: A number of new algorithms have larger constructs. Now we have functions as binds in
been added as well. Such as ALL OFF, ANY OFF, COPY standard library, std::function &std:: bind, which is
IF,MOVE is sorted and various others. power full and expressive.
c. Pointers: standard small pointers are been
7.2 Immutable data
completely upgraded. Replacing alter pointer which
were never very satisfactory. Std::unique_ptr provides Once object is created, data is not changed, if it is
a single owner of small pointer, while std:shared_ptr required to be changed, new object is created.
allow shared use, a std::week_ptr holds a reference Mutation may create copy, string in java and C# also
but has no concept of owner ship, and that is useful in works on it. It has several advantages, first it helps
scenario such as cashes with concurrency. Because variable is not going to
d. Functional: Although C++ is not widely known as change, while using it. And reasoning about code,
functional programming language, but C++ 11 added once you create them you know while this code is for?
new features that make it easier to make it in the If we create a copy every time variable change his
functional programming style. std::function is used to state in that fashion, but that is not necessary is the
represent a callable target which can be a function case. Lets consider a simple example
pointer, function object or lamda and this make it
much simpler to manipulate functions. std::bind
provides a mechanism for partial function application.
Taking a function binding one or more of its
arguments than returning a new function.
e. Concurrency: prior to C++11 all concurrency
functionality were platform dependent making it hard
to write a portable code, but this no longer the case in Figure: 5
C++11.
We have link list and a pointer p, points first element,
7. Functional Programming (FP) if we add a new element at head then it is simple,
In this section we will discuss some unique and
powerful feature of functional programing, before
this, it is important to know about what is FP? Why it
is so important to develop to in C++? It is a type of
programming that focusing on functional execution as
its main computational mechanism. It is a concise and
efficient way to write algorithmic code. And this is the Figure: 6
new style of programming as it introduced many new
patterns. [15] The best thing about functional New element link to the rest and no copying is
programming is, it is supported by functional required most importantly, point p is still valid
language. You can program in a functional style and pointing to the original values, point q , points to the
one thing C++ make FP much easier. Why we need of new sequence.
functional programming? What if we want to add new element to the tail of the
Followings are some reasons why we need functional list then, in this case we have to copy the list, if point
107
different concepts of FP like filter, MAP and reduce as 8. H. Albin-Amiot, P. Cointe, Y. G.Gueheneuc, and N.
well. Experience, continuous practices have made the Jussien. Instantiating and detecting design
C++ to work in a completely new environment. patterns: putting bits and pieces together. In 16th
AnnuInternational Conference on Automated
References
Software Engineering (ASE 2001), pages 2629,
1. E. Casais, An Object-Oriented System San Diego, CA, USA, 2001. Ecole des Mines Nantes
Implementing KNOs, Proceedings of the France.
Conference on Office Information Systems (COIS), 9. G. Antoniol, G. Casazza, M. Di Penta, and R.
pp. 284-290, Palo Alto, March 1988. Fiutem. Object-oriented design patterns
2. Esterie, P., Falcou, J., Gaunard, M., Laprest, J. T., recovery. Journal of Systems and Software,
&Lacassagne, L. (2014). The numerical template 59(2):181196, 2001.
toolbox: A modern C++ design for scientific 10. R.B. France, D.-K. Kim, Sudipto Ghosh, and E.
computing. Journal of Parallel and Distributed Song. Auml-based pattern specification
Computing, 74(12), 3240-3253. technique. Software Engineering, IEEET
3. Schmidt, D. C., Stal, M., Rohnert, H., & ransactions on, 30(3): 193206, 2004.
Buschmann, F. (2013). Pattern-Oriented Software 11. Cargill, Tom. Localized Ownership: Managing
Architecture, Patterns for Concurrent and Dynamic Objects in C++. Pattern Languages of
Networked Objects (Vol. 2). John Wiley & Sons. Program Design 2. John M. Vlissides et al., eds.
4. Garca Snchez, J. D., & Stroustrup, B. (2015). Reading, MA: Addison-Wesley, 1996
Improving performance and maintainability 12. Martin, R. Design Patterns for Dealing with Dual
through refactoring in C++ 11. Inheritance Hierarchies in C++.SIGS Publications:
5. Aragn, A. M. (2014). A C++ 11 implementation of C++ Report, April, 1997.
arbitrary-rank tensors for high-performance 13. Gamma, E. (1995). Design patterns: Elements Of
computing. Computer Physics Reusable Object-Oriented Software. Pearson
Communications, 185(6), 1681-1696. Education India.
6. B. Stroustrup, the C++ Programming 14. Orlov, S., & Melnikova, N. (2015). Compound
Language, Addison-Wesley, Reading, Mass., Object Model for Scalable System Development in
1986. C++. Procedia Computer Science, 66, 651-660.
7. A Pattern Language: Towns, Buildings, 15. Oliveira, C. (2016). Functional Programming
Construction (Center for Environmental Structure) Techniques. In Options and Derivatives
(17 August 1977) by Christopher Alexander, Sara Programming in C++ (pp. 127-142). Apress.
Ishikawa, Murray Silverstein
109
Page