SlideShare a Scribd company logo
1 of 7
Download to read offline
SOM-ITSOLUTIONS
C++
Copy-On-Write (COW)
SOMENATH MUKHOPADHYAY
som-itsolutions
#A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282
Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com
Website:​ ​http://www.som-itsolutions.com/
Blog: ​www.som-itsolutions.blogspot.com
As i was trying to recapitulate several important concepts of OOAD, naturally COW or
Copy-On-Write got my attention for sometime. COW is a special technique used for efficient
resource management in computer science. In C++ ‘98 standard, COW was used to define
the std::string class. Although in C++ ‘11 standard, COW is not used to define the string
class of the standard C++ library, but it is worth to have a look at the earlier implementation
of the string class in GCC’s standard library. In COW, we defer creating of a new modifiable
resource of a class in the case of copying if we keep the copy unchanged. We just refer to
the old resource in the new copy. We write only when the copy changes that modifiable
resource.
The following code is my effort to explain the COW concept in a String class. Let me explain
some of the parts of this working code.
#include​ ​<string.h>
#include​ ​<cstddef>
//This is using default constructor
//and copy constructor. Hence while copying it will
//use shallow copy.
class​ ​StringHolder​{
public​:
char​*​ data;
int​ refCount;
virtual​ ​~​StringHolder(){
delete​[] data;
}
};
class​ ​MyString​{
private​:
StringHolder​*​ mStrHolder;
int​ length;
public​:
//default constructor
MyString(){
mStrHolder ​=​ ​new​ StringHolder();
length ​=​ ​0​;
}
MyString(​const​ ​char​*​ inStr){
mStrHolder ​=​ ​new​ StringHolder();
unsigned​ l​=​strlen(inStr);
mStrHolder​->​data​=​new​ ​char​[l​+​1​];
memcpy(mStrHolder​->​data,inStr,l​+​1​);
mStrHolder​->​refCount ​=​ ​1​;
length ​=​ l;
}
MyString(​const​ MyString​&​ inStr){
mStrHolder ​=​ inStr.mStrHolder;
mStrHolder​->​refCount​++​;
length ​=​ inStr.length;
}
//Reference counted assignment operator
MyString​&​ ​operator​=​(​const​ MyString​&​ inStr){
//check against self assignment
if​(​this​ ​==​ ​&​inStr)
return​ ​*​this​;
mStrHolder​->​refCount​--​;​//the data of the lhs string
//does no longer point to the old char
//array
if​(mStrHolder​->​refCount ​==​ ​0​)
delete​ mStrHolder;
mStrHolder ​=​ inStr.mStrHolder;​//the lhs and rhs data
//both are pointing to the RHS data.
mStrHolder​->​refCount​++​;
length ​=​ inStr.length;
return​ ​*​this​;
}
//mutator service
MyString​&​ ​operator​+=​(​const​ MyString​&​ inStr){
Detach();
const​ ​char​*​ cStr ​=​ inStr.c_str();
int​ l ​=​ inStr.length;
const​ ​char​*​ oldData ​=​ mStrHolder​->​data;
//deep copy
char​*​ tmp​=​new​ ​char​[length ​+​ l];
mStrHolder​->​data ​=​ tmp;
memcpy(mStrHolder​->​data, oldData, length);
strcat(mStrHolder​->​data,cStr);
mStrHolder​->​refCount​=​1​;
length​+=​ l;
return​ ​*​this​;
}
//Destructor. The virtual term is important
virtual​ ​~​MyString(){
mStrHolder​->​refCount​--​;
if​(mStrHolder​->​refCount ​==​ ​0​)
delete​ mStrHolder;
}
//Call this function first for all the
//mutator services of this class
void​ Detach(){
if​ (mStrHolder​->​refCount ​==​ ​1​)
return​;
StringHolder​*​ temp ​=​ ​new​ StringHolder();
temp​->​data ​=​ mStrHolder​->​data;
temp​->​refCount ​=​ ​1​;
mStrHolder​->​refCount​--​;
mStrHolder ​=​ temp;
}
inline​ ​char​*​ c_str()
{
return​ (mStrHolder​->​data);
}
inline​ ​const​ ​char​*​ c_str() ​const
{
return​ (mStrHolder​->​data);
}
int​ getRefCount(){
return​ mStrHolder​->​refCount;
}
};
As you can see, there is a class called StringHolder which is responsible to store the actual
data or the character array. As I have not used any constructor or copy constructor, naturally
this class will take the help of compiler generated default constructor and copy constructor.
And as the compiler generated copy constructor does shallow copy, hence this class will
also use shallow copy in case of copy constructor. Beside the character array, this class has
a reference count member variable which actually determines how many of our user defined
String class actually are holding a reference to the character array at any particular time.
Now let us turn our attention to the MyString class. As you can see, there is a default
constructor in this class, one copy constructor, one assignment operator and a destructor.
These kinds of classes are called Canonical Classes in C++.
The class also has an one argument constructor which creates the MyString objects from a
character array. Now let us examine the copy constructor. As you can see, inside the copy
constructor we are simply taking the help of the shallow copy of the MyString’s member
variable mStrHolder. Hence whenever we call a copy constructor, an extra reference is
added to the character array of the StringHolder class. So we need to increase the refCount
member variable as well.
Now let us examine the assignment operator. The first line checks for the self assignment
that probably i don’t need to explain here. Next as we are assigning a new value to the LHS,
the original LHS will no longer refer to the old character array of the StringHolder class.
Hence we have decremented the reference count by one. Next we are doing a shallow copy
of the mStrHolder member variable of the MyString class, and as a result we are just
incrementing the reference count.
Now let us pay attention to a mutator member functions of this class. We have implemented
only one of such functions and that is we have defined the += operator overloading. The
other mutator functions can be implemented in the same fashion.
We have implemented a Detach() method to help us define the mutator methods. We have
to call this Detach() method at the beginning of any mutator functions of the MyString class.
Let us examine what this Detach method is doing.
//Call this function first for all the
//mutator services of this class
void​ Detach(){
if​ (mStrHolder​->​refCount ​==​ ​1​)
return​;
StringHolder​*​ temp ​=​ ​new​ StringHolder();
temp​->​data ​=​ mStrHolder​->​data;
temp​->​refCount ​=​ ​1​;
mStrHolder​->​refCount​--​;
mStrHolder ​=​ temp;
}
As you can see, whenever we call the Detach() method, it reduces the old mStringHolder’s
refCount by one and creates a new mStrHolder object with a reference count 1.
Having explained the Detach() method, now let us focus on += mutator method of the class.
As you can see from the definition of the += operator overloading method that we have first
called the Detach() method. As a result the LHS will have a brand new mStrHolder object
with a reference count of 1. Then later as you can see that we have used a deep copy of the
mStrHolder class for the output result. Hence the output of this += operator overloading will
be a brand new object having a single reference to the character array. At the same time,
the original reference count of the LHS will be reduced by one.
That’s it.
So let me explain from an user’s perspective of what is happening in this COW based string
class. To experiment with this class i have created few lines of code as follow.
MyString str1("Loves to study CPP...");
MyString str2("How are you?");
MyString str3("Somenath Mukhopadhyay");
Naturally all of the above strings will have a reference count of 1.
Now if we do str2 = str1, what will happen. As you can understand that now both str1 and
str2 will point to the same character array. Hence the reference count will be 2. We can
verify that by the following piece of code.
char* data1 = str1.c_str();
char* data2 = str2.c_str();
printf("%pn",&data1[0]);
printf("%pn",&data2[0]);
We will see that both of the outputs of the above code are same which implies that both str1
and str2 are referring to the same character array.
Now what will happen if we write MyString str4(str2). So now both str1, str2 and str4 are
pointing to the same character array. Hence the reference count will be 3. We can again
verify that by using the following code.
char* data1 = str1.c_str();
char* data2 = str2.c_str();
char* data4 = str4.c_str();
printf("%pn",&data1[0]);
printf("%pn",&data2[0]);
printf("%pn",&data4[0]);
As you can see in all of the above functions we are actually not creating any new strings
except for the first time. We are just incrementing the reference count.
Now the interesting part. What will happen if we do str1+=str2. In this case a brand new str1
will be created and the old str1’s reference to the character array will be lost. Hence after this
operation only str2 and str4 will hold a pointer to the character array. We can again verify
this by the following code.
char* data1 = str1.c_str();
char* data2 = str2.c_str();
char* data4 = str4.c_str();
printf("%pn",&data1[0]);
printf("%pn",&data2[0]);
printf("%pn",&data4[0]);
All of the above steps have been pictorially described in the following diagram.

More Related Content

What's hot (20)

pairs
pairspairs
pairs
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Strings
StringsStrings
Strings
 
Strings in c
Strings in cStrings in c
Strings in c
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
Chap 8(strings)
Chap 8(strings)Chap 8(strings)
Chap 8(strings)
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Strings
StringsStrings
Strings
 
The string class
The string classThe string class
The string class
 
Array and string
Array and stringArray and string
Array and string
 
String.ppt
String.pptString.ppt
String.ppt
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 
14 strings
14 strings14 strings
14 strings
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
 
Strings
StringsStrings
Strings
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Team 1
Team 1Team 1
Team 1
 

Viewers also liked

Viewers also liked (15)

Twitter para el pequeño negocio
Twitter para el pequeño negocioTwitter para el pequeño negocio
Twitter para el pequeño negocio
 
Volume 11 matemática financeira
Volume 11   matemática financeiraVolume 11   matemática financeira
Volume 11 matemática financeira
 
Recebendo amigos
Recebendo amigosRecebendo amigos
Recebendo amigos
 
Introduction to BTRFS and ZFS
Introduction to BTRFS and ZFSIntroduction to BTRFS and ZFS
Introduction to BTRFS and ZFS
 
Zsv plakats
Zsv plakatsZsv plakats
Zsv plakats
 
Trabajo de religion hinduismo
Trabajo de religion hinduismoTrabajo de religion hinduismo
Trabajo de religion hinduismo
 
Vpd grafiks 2017
Vpd grafiks 2017Vpd grafiks 2017
Vpd grafiks 2017
 
hinduismo
hinduismohinduismo
hinduismo
 
Apache Jackrabbit Oak on MongoDB
Apache Jackrabbit Oak on MongoDBApache Jackrabbit Oak on MongoDB
Apache Jackrabbit Oak on MongoDB
 
Day 3: ¿Cómo llevar un curso presencial a B-learning?
Day 3: ¿Cómo llevar un curso presencial a B-learning?Day 3: ¿Cómo llevar un curso presencial a B-learning?
Day 3: ¿Cómo llevar un curso presencial a B-learning?
 
Day 2: Conferencia Magistral: Visión de Chamilo al 2020
Day 2: Conferencia Magistral: Visión de Chamilo al 2020 Day 2: Conferencia Magistral: Visión de Chamilo al 2020
Day 2: Conferencia Magistral: Visión de Chamilo al 2020
 
Budismo
BudismoBudismo
Budismo
 
Genital prolapse
Genital prolapseGenital prolapse
Genital prolapse
 
Achieving your dreams and Goal Setting
Achieving your dreams and Goal SettingAchieving your dreams and Goal Setting
Achieving your dreams and Goal Setting
 
BNG Company Profile
BNG Company ProfileBNG Company Profile
BNG Company Profile
 

Similar to Copy on write

C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYRajeshkumar Reddy
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3Mohamed Ahmed
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184Mahmoud Samir Fayed
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 

Similar to Copy on write (20)

C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Lecture5
Lecture5Lecture5
Lecture5
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Bc0037
Bc0037Bc0037
Bc0037
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Sharbani bhattacharya VB Structures
Sharbani bhattacharya VB StructuresSharbani bhattacharya VB Structures
Sharbani bhattacharya VB Structures
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Overloading
OverloadingOverloading
Overloading
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184The Ring programming language version 1.5.3 book - Part 23 of 184
The Ring programming language version 1.5.3 book - Part 23 of 184
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 

More from Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trieSomenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidSomenath Mukhopadhyay
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsSomenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docsSomenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidSomenath Mukhopadhyay
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in JavaSomenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsSomenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureSomenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternSomenath Mukhopadhyay
 

More from Somenath Mukhopadhyay (20)

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Uml training
Uml trainingUml training
Uml training
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 

Recently uploaded

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
 
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
 
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.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
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
 
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
 
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
 
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
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
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
 
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.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

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-...
 
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...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
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
 
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
 
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 ...
 
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
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
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...
 
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 ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Copy on write

  • 1. SOM-ITSOLUTIONS C++ Copy-On-Write (COW) SOMENATH MUKHOPADHYAY som-itsolutions #A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282 Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com Website:​ ​http://www.som-itsolutions.com/ Blog: ​www.som-itsolutions.blogspot.com
  • 2. As i was trying to recapitulate several important concepts of OOAD, naturally COW or Copy-On-Write got my attention for sometime. COW is a special technique used for efficient resource management in computer science. In C++ ‘98 standard, COW was used to define the std::string class. Although in C++ ‘11 standard, COW is not used to define the string class of the standard C++ library, but it is worth to have a look at the earlier implementation of the string class in GCC’s standard library. In COW, we defer creating of a new modifiable resource of a class in the case of copying if we keep the copy unchanged. We just refer to the old resource in the new copy. We write only when the copy changes that modifiable resource. The following code is my effort to explain the COW concept in a String class. Let me explain some of the parts of this working code. #include​ ​<string.h> #include​ ​<cstddef> //This is using default constructor //and copy constructor. Hence while copying it will //use shallow copy. class​ ​StringHolder​{ public​: char​*​ data; int​ refCount; virtual​ ​~​StringHolder(){ delete​[] data; } }; class​ ​MyString​{ private​: StringHolder​*​ mStrHolder; int​ length; public​: //default constructor MyString(){ mStrHolder ​=​ ​new​ StringHolder(); length ​=​ ​0​; } MyString(​const​ ​char​*​ inStr){ mStrHolder ​=​ ​new​ StringHolder(); unsigned​ l​=​strlen(inStr); mStrHolder​->​data​=​new​ ​char​[l​+​1​]; memcpy(mStrHolder​->​data,inStr,l​+​1​); mStrHolder​->​refCount ​=​ ​1​;
  • 3. length ​=​ l; } MyString(​const​ MyString​&​ inStr){ mStrHolder ​=​ inStr.mStrHolder; mStrHolder​->​refCount​++​; length ​=​ inStr.length; } //Reference counted assignment operator MyString​&​ ​operator​=​(​const​ MyString​&​ inStr){ //check against self assignment if​(​this​ ​==​ ​&​inStr) return​ ​*​this​; mStrHolder​->​refCount​--​;​//the data of the lhs string //does no longer point to the old char //array if​(mStrHolder​->​refCount ​==​ ​0​) delete​ mStrHolder; mStrHolder ​=​ inStr.mStrHolder;​//the lhs and rhs data //both are pointing to the RHS data. mStrHolder​->​refCount​++​; length ​=​ inStr.length; return​ ​*​this​; } //mutator service MyString​&​ ​operator​+=​(​const​ MyString​&​ inStr){ Detach(); const​ ​char​*​ cStr ​=​ inStr.c_str(); int​ l ​=​ inStr.length; const​ ​char​*​ oldData ​=​ mStrHolder​->​data; //deep copy char​*​ tmp​=​new​ ​char​[length ​+​ l]; mStrHolder​->​data ​=​ tmp; memcpy(mStrHolder​->​data, oldData, length); strcat(mStrHolder​->​data,cStr); mStrHolder​->​refCount​=​1​; length​+=​ l; return​ ​*​this​; }
  • 4. //Destructor. The virtual term is important virtual​ ​~​MyString(){ mStrHolder​->​refCount​--​; if​(mStrHolder​->​refCount ​==​ ​0​) delete​ mStrHolder; } //Call this function first for all the //mutator services of this class void​ Detach(){ if​ (mStrHolder​->​refCount ​==​ ​1​) return​; StringHolder​*​ temp ​=​ ​new​ StringHolder(); temp​->​data ​=​ mStrHolder​->​data; temp​->​refCount ​=​ ​1​; mStrHolder​->​refCount​--​; mStrHolder ​=​ temp; } inline​ ​char​*​ c_str() { return​ (mStrHolder​->​data); } inline​ ​const​ ​char​*​ c_str() ​const { return​ (mStrHolder​->​data); } int​ getRefCount(){ return​ mStrHolder​->​refCount; } }; As you can see, there is a class called StringHolder which is responsible to store the actual data or the character array. As I have not used any constructor or copy constructor, naturally this class will take the help of compiler generated default constructor and copy constructor. And as the compiler generated copy constructor does shallow copy, hence this class will also use shallow copy in case of copy constructor. Beside the character array, this class has a reference count member variable which actually determines how many of our user defined String class actually are holding a reference to the character array at any particular time. Now let us turn our attention to the MyString class. As you can see, there is a default constructor in this class, one copy constructor, one assignment operator and a destructor. These kinds of classes are called Canonical Classes in C++.
  • 5. The class also has an one argument constructor which creates the MyString objects from a character array. Now let us examine the copy constructor. As you can see, inside the copy constructor we are simply taking the help of the shallow copy of the MyString’s member variable mStrHolder. Hence whenever we call a copy constructor, an extra reference is added to the character array of the StringHolder class. So we need to increase the refCount member variable as well. Now let us examine the assignment operator. The first line checks for the self assignment that probably i don’t need to explain here. Next as we are assigning a new value to the LHS, the original LHS will no longer refer to the old character array of the StringHolder class. Hence we have decremented the reference count by one. Next we are doing a shallow copy of the mStrHolder member variable of the MyString class, and as a result we are just incrementing the reference count. Now let us pay attention to a mutator member functions of this class. We have implemented only one of such functions and that is we have defined the += operator overloading. The other mutator functions can be implemented in the same fashion. We have implemented a Detach() method to help us define the mutator methods. We have to call this Detach() method at the beginning of any mutator functions of the MyString class. Let us examine what this Detach method is doing. //Call this function first for all the //mutator services of this class void​ Detach(){ if​ (mStrHolder​->​refCount ​==​ ​1​) return​; StringHolder​*​ temp ​=​ ​new​ StringHolder(); temp​->​data ​=​ mStrHolder​->​data; temp​->​refCount ​=​ ​1​; mStrHolder​->​refCount​--​; mStrHolder ​=​ temp; } As you can see, whenever we call the Detach() method, it reduces the old mStringHolder’s refCount by one and creates a new mStrHolder object with a reference count 1. Having explained the Detach() method, now let us focus on += mutator method of the class. As you can see from the definition of the += operator overloading method that we have first called the Detach() method. As a result the LHS will have a brand new mStrHolder object with a reference count of 1. Then later as you can see that we have used a deep copy of the mStrHolder class for the output result. Hence the output of this += operator overloading will be a brand new object having a single reference to the character array. At the same time, the original reference count of the LHS will be reduced by one.
  • 6. That’s it. So let me explain from an user’s perspective of what is happening in this COW based string class. To experiment with this class i have created few lines of code as follow. MyString str1("Loves to study CPP..."); MyString str2("How are you?"); MyString str3("Somenath Mukhopadhyay"); Naturally all of the above strings will have a reference count of 1. Now if we do str2 = str1, what will happen. As you can understand that now both str1 and str2 will point to the same character array. Hence the reference count will be 2. We can verify that by the following piece of code. char* data1 = str1.c_str(); char* data2 = str2.c_str(); printf("%pn",&data1[0]); printf("%pn",&data2[0]); We will see that both of the outputs of the above code are same which implies that both str1 and str2 are referring to the same character array. Now what will happen if we write MyString str4(str2). So now both str1, str2 and str4 are pointing to the same character array. Hence the reference count will be 3. We can again verify that by using the following code. char* data1 = str1.c_str(); char* data2 = str2.c_str(); char* data4 = str4.c_str(); printf("%pn",&data1[0]); printf("%pn",&data2[0]); printf("%pn",&data4[0]); As you can see in all of the above functions we are actually not creating any new strings except for the first time. We are just incrementing the reference count. Now the interesting part. What will happen if we do str1+=str2. In this case a brand new str1 will be created and the old str1’s reference to the character array will be lost. Hence after this operation only str2 and str4 will hold a pointer to the character array. We can again verify this by the following code.
  • 7. char* data1 = str1.c_str(); char* data2 = str2.c_str(); char* data4 = str4.c_str(); printf("%pn",&data1[0]); printf("%pn",&data2[0]); printf("%pn",&data4[0]); All of the above steps have been pictorially described in the following diagram.