473,320 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Deep versus Shallow Copy - Part 2

2.0 Sample Code

class ABC // dummy class used below
{};

class Example2
{
public:
Example2(); // default ctor
Example2( const Example2 &); // copy ctor
Example2 & operator = (const Example2 &); // overloaded
// assignment operator
~Example2(); //dtor
private:
int ii;
double dd;
ABC * abcPtr; // will point to a dynamically created ABC object
};
// default ctor
Example2::Example2()
{
abcPtr = new ABC; // dynamically create an ABC object and have
// the class member abcPtr point to it.
ii = 10; // assign some value
dd = 3.765; // assign some value
}
// copy ctor
Example2::Example2(const Example2 & src)
:ii(src.ii),dd(src.dd) // MIL
{
abcPtr = new ABC; // Same as default ctor above.
*abcPtr = *(src.abcPtr); // Do a deep copy.
}
// dtor
Example2::~Example2()
{
delete abcPtr; //Destroy the dynamically created ABC object.
abcPtr = 0; //Not necessary, but prevents a calamity if an
// attempt is made to destroy the same
// ABC object a second time.
}

// overloaded assignement operator
Example2 & Example2::operator = (const Example2 & RHS)
{
//First check that the operand on the Right Hand Side (RHS)
// of the assignment operator is not the exact same object
// as the operand on the LHS of the assignment operator.
// We do this by testing to see if both objects have the
// same address!

if (this == &RHS) // if true, we are done!
{
return *this; // return the original LHS operand
}
else // we still have some work to do
{
ii = RHS.ii; // a shallow copy is good enough here
dd = RHS.dd; // here as well

*abcPtr = *(RHS.abcPtr); // here we need a deep copy.

return *this; // return the modified LHS operand.
}
}
// Simple program to test our Example2 class
int main()
{
Example2 ex2_1, ex2_2; // Will invoke default ctor (twice).

ex2_1 = ex2_2; // Will invoke overloaded Assignment operator.

Example2 ex2_3(ex2_1); // Will invoke copy ctor.

return 0; // We are finished!

} // end of main() - Example2 dtor will be invoked 3 times

Nov 26 '06 #1
9 1648

blangela skrev:
2.0 Sample Code

class ABC // dummy class used below
{};

class Example2
{
public:
Example2(); // default ctor
Example2( const Example2 &); // copy ctor
Example2 & operator = (const Example2 &); // overloaded
// assignment operator
~Example2(); //dtor
private:
int ii;
double dd;
ABC * abcPtr; // will point to a dynamically created ABC object
};
// default ctor
Example2::Example2()
{
abcPtr = new ABC; // dynamically create an ABC object and have
// the class member abcPtr point to it.
ii = 10; // assign some value
dd = 3.765; // assign some value
}
// copy ctor
Example2::Example2(const Example2 & src)
:ii(src.ii),dd(src.dd) // MIL
{
abcPtr = new ABC; // Same as default ctor above.
*abcPtr = *(src.abcPtr); // Do a deep copy.
}
// dtor
Example2::~Example2()
{
delete abcPtr; //Destroy the dynamically created ABC object.
abcPtr = 0; //Not necessary, but prevents a calamity if an
// attempt is made to destroy the same
// ABC object a second time.
}

// overloaded assignement operator
Example2 & Example2::operator = (const Example2 & RHS)
{
//First check that the operand on the Right Hand Side (RHS)
// of the assignment operator is not the exact same object
// as the operand on the LHS of the assignment operator.
// We do this by testing to see if both objects have the
// same address!

if (this == &RHS) // if true, we are done!
{
return *this; // return the original LHS operand
}
else // we still have some work to do
{
ii = RHS.ii; // a shallow copy is good enough here
dd = RHS.dd; // here as well

*abcPtr = *(RHS.abcPtr); // here we need a deep copy.

return *this; // return the modified LHS operand.
}
}
// Simple program to test our Example2 class
int main()
{
Example2 ex2_1, ex2_2; // Will invoke default ctor (twice).

ex2_1 = ex2_2; // Will invoke overloaded Assignment operator.

Example2 ex2_3(ex2_1); // Will invoke copy ctor.

return 0; // We are finished!

} // end of main() - Example2 dtor will be invoked 3 times
I believe that the code above is a typical example of real code, but
anyway it is bad code. A rule of thumb is that code in a class should
be centered around the purpose of the class itself ("the class, the
whole class and nothing but the class"), and the above code is mainly
centered on copying a pointer!
My recommendation is that you learn your students (basic) template
programming before pointers. This should enable your students to write
a safe-pointer template for the class above without obfuscating
anything.

Kind regards
Peter

Nov 26 '06 #2

peter koch wrote:
blangela skrev:
2.0 Sample Code

class ABC // dummy class used below
{};

class Example2
{
public:
Example2(); // default ctor
Example2( const Example2 &); // copy ctor
Example2 & operator = (const Example2 &); // overloaded
// assignment operator
~Example2(); //dtor
private:
int ii;
double dd;
ABC * abcPtr; // will point to a dynamically created ABC object
};
// default ctor
Example2::Example2()
{
abcPtr = new ABC; // dynamically create an ABC object and have
// the class member abcPtr point to it.
ii = 10; // assign some value
dd = 3.765; // assign some value
}
// copy ctor
Example2::Example2(const Example2 & src)
:ii(src.ii),dd(src.dd) // MIL
{
abcPtr = new ABC; // Same as default ctor above.
*abcPtr = *(src.abcPtr); // Do a deep copy.
}
// dtor
Example2::~Example2()
{
delete abcPtr; //Destroy the dynamically created ABC object.
abcPtr = 0; //Not necessary, but prevents a calamity if an
// attempt is made to destroy the same
// ABC object a second time.
}

// overloaded assignement operator
Example2 & Example2::operator = (const Example2 & RHS)
{
//First check that the operand on the Right Hand Side (RHS)
// of the assignment operator is not the exact same object
// as the operand on the LHS of the assignment operator.
// We do this by testing to see if both objects have the
// same address!

if (this == &RHS) // if true, we are done!
{
return *this; // return the original LHS operand
}
else // we still have some work to do
{
ii = RHS.ii; // a shallow copy is good enough here
dd = RHS.dd; // here as well

*abcPtr = *(RHS.abcPtr); // here we need a deep copy.

return *this; // return the modified LHS operand.
}
}
// Simple program to test our Example2 class
int main()
{
Example2 ex2_1, ex2_2; // Will invoke default ctor (twice).

ex2_1 = ex2_2; // Will invoke overloaded Assignment operator.

Example2 ex2_3(ex2_1); // Will invoke copy ctor.

return 0; // We are finished!

} // end of main() - Example2 dtor will be invoked 3 times

I believe that the code above is a typical example of real code, but
anyway it is bad code. A rule of thumb is that code in a class should
be centered around the purpose of the class itself ("the class, the
whole class and nothing but the class"), and the above code is mainly
centered on copying a pointer!
My recommendation is that you learn your students (basic) template
programming before pointers. This should enable your students to write
a safe-pointer template for the class above without obfuscating
anything.

Kind regards
Peter
Thanks for your suggestion Peter. Can you point me to a C++ text I can
use for my course that:

a) covers templates before pointers
b) teaches the "good code" way of doing what I am trying to teach in my
code example above

I have learned the hard way that if the text does not reasonably
closely follow the course, the typical student will be extemely
unhappy.

Thanks in advance,

Bob

Thanks

Nov 26 '06 #3
In article <11**********************@l12g2000cwl.googlegroups .com>,
"blangela" <Bo***********@telus.netwrote:
Thanks for your suggestion Peter. Can you point me to a C++ text I can
use for my course that:

a) covers templates before pointers
b) teaches the "good code" way of doing what I am trying to teach in my
code example above

I have learned the hard way that if the text does not reasonably
closely follow the course, the typical student will be extemely
unhappy.
At the risk of answering for Peter,

Accelerated C++
Koenig & Moo
http://www.acceleratedcpp.com/

This is the most highly regarded introductory C++ book available today.
I have a copy myself. I regret that I have not read all of it, but I
have skimmed it. And I deeply regret that this book was not available
when I was learning C++.

From the online table of contents:

http://www.acceleratedcpp.com/details/contents.html
Chapter 8 Writing generic functions
....
Chapter 10 Managing memory and low-level data structures
10.1 Pointers and arrays
One of the really nice things about this book is that it teaches good
style right from the start. And it starts with high level stuff, not
low level stuff. The student learns to write amazingly useful programs
from day 1 using the std::lib. Defining one's own types and managing
memory are covered later.

If I were teaching an introductory course on C++, I would not even think
of using anything else.

No, I don't have a financial interest in this book. I wish I did
though. :-)

-Howard
Committee member WG21 (C++ Programming Language)
Library Working Group Chairman
Nov 26 '06 #4

blangela skrev:
peter koch wrote:
[snip]

I believe that the code above is a typical example of real code, but
anyway it is bad code. A rule of thumb is that code in a class should
be centered around the purpose of the class itself ("the class, the
whole class and nothing but the class"), and the above code is mainly
centered on copying a pointer!
My recommendation is that you learn your students (basic) template
programming before pointers. This should enable your students to write
a safe-pointer template for the class above without obfuscating
anything.

Kind regards
Peter

Thanks for your suggestion Peter. Can you point me to a C++ text I can
use for my course that:

a) covers templates before pointers
b) teaches the "good code" way of doing what I am trying to teach in my
code example above

I have learned the hard way that if the text does not reasonably
closely follow the course, the typical student will be extemely
unhappy.

Thanks in advance,

Bob
Hi Bob

I am happy that Hinnant could answer for me, as I haven't had the
chance to read any suitable beginners book. I learned C++ partially
from Stroustrups books and luckily from some collegues who already knew
how to C++ (no - far from every C++ programmer knows that!).
All sources speak very highly about Accelerated C++ so jump ahead and
buy the book.
Good luck with your teaching.

/Peter

Nov 26 '06 #5

Howard Hinnant wrote:
In article <11**********************@l12g2000cwl.googlegroups .com>,
"blangela" <Bo***********@telus.netwrote:
Thanks for your suggestion Peter. Can you point me to a C++ text I can
use for my course that:

a) covers templates before pointers
b) teaches the "good code" way of doing what I am trying to teach in my
code example above

I have learned the hard way that if the text does not reasonably
closely follow the course, the typical student will be extemely
unhappy.

At the risk of answering for Peter,

Accelerated C++
Koenig & Moo
http://www.acceleratedcpp.com/

This is the most highly regarded introductory C++ book available today.
I have a copy myself. I regret that I have not read all of it, but I
have skimmed it. And I deeply regret that this book was not available
when I was learning C++.

From the online table of contents:

http://www.acceleratedcpp.com/details/contents.html
Chapter 8 Writing generic functions
...
Chapter 10 Managing memory and low-level data structures
10.1 Pointers and arrays

One of the really nice things about this book is that it teaches good
style right from the start. And it starts with high level stuff, not
low level stuff. The student learns to write amazingly useful programs
from day 1 using the std::lib. Defining one's own types and managing
memory are covered later.

If I were teaching an introductory course on C++, I would not even think
of using anything else.

No, I don't have a financial interest in this book. I wish I did
though. :-)

-Howard
Committee member WG21 (C++ Programming Language)
Library Working Group Chairman
Thanks Howard. I will see if my school can get me a desk copy to
evaluate.

Bob

Nov 27 '06 #6

peter koch wrote:
blangela skrev:
peter koch wrote:
[snip]
>
I believe that the code above is a typical example of real code, but
anyway it is bad code. A rule of thumb is that code in a class should
be centered around the purpose of the class itself ("the class, the
whole class and nothing but the class"), and the above code is mainly
centered on copying a pointer!
My recommendation is that you learn your students (basic) template
programming before pointers. This should enable your students to write
a safe-pointer template for the class above without obfuscating
anything.
>
Kind regards
Peter
Thanks for your suggestion Peter. Can you point me to a C++ text I can
use for my course that:

a) covers templates before pointers
b) teaches the "good code" way of doing what I am trying to teach in my
code example above

I have learned the hard way that if the text does not reasonably
closely follow the course, the typical student will be extemely
unhappy.

Thanks in advance,

Bob
Hi Bob

I am happy that Hinnant could answer for me, as I haven't had the
chance to read any suitable beginners book. I learned C++ partially
from Stroustrups books and luckily from some collegues who already knew
how to C++ (no - far from every C++ programmer knows that!).
All sources speak very highly about Accelerated C++ so jump ahead and
buy the book.
Good luck with your teaching.

/Peter
I had a look at the table of contents and some important topics seem to
be missing. For example exception handling and operator overloading .

Nov 27 '06 #7
On Nov 27, 5:32 am, "blangela" <Bob_Langel...@telus.netwrote:
peter koch wrote:
I am happy that Hinnant could answer for me, as I haven't had the
chance to read any suitable beginners book. I learned C++ partially
from Stroustrups books and luckily from some collegues who already knew
how to C++ (no - far from every C++ programmer knows that!).
All sources speak very highly about Accelerated C++ so jump ahead and
buy the book.
Good luck with your teaching.
/PeterI had a look at the table of contents and some important topics seem to
be missing. For example exception handling and operator overloading .
I don't own a copy of the book, but I'd suspect that at least
overloading of the assignment-operator is covered somewhere. And
chapter 12 "Making class objects act like values", sounds like it might
include more overloading of operators.

--
Erik Wikström

Nov 27 '06 #8

blangela skrev:
peter koch wrote:
blangela skrev:
peter koch wrote:
[snip]
[snip]
I am happy that Hinnant could answer for me, as I haven't had the
chance to read any suitable beginners book. I learned C++ partially
from Stroustrups books and luckily from some collegues who already knew
how to C++ (no - far from every C++ programmer knows that!).
All sources speak very highly about Accelerated C++ so jump ahead and
buy the book.
Good luck with your teaching.

/Peter

I had a look at the table of contents and some important topics seem to
be missing. For example exception handling and operator overloading .
Hi Bob

I just downloaded the code and it seems that throw is introduced in
chapter 4 while operator overloading is used in chapter 14. So (of
course!) those subjects are covered too.
Kind regards
Peter

Nov 27 '06 #9
In article <11**********************@h54g2000cwb.googlegroups .com>,
"blangela" <Bo***********@telus.netwrote:
I had a look at the table of contents and some important topics seem to
be missing. For example exception handling and operator overloading .
Fwiw, exception throwing/catching is introduced in chapter 4, but there
is no section devoted to the subject. Rather it is simply added to an
ongoing example. I don't know if the book covers exception safety.
After glancing at the index my best guess would be no.

There's a decent treatment of exception safety here:

http://www.research.att.com/~bs/3rd_safe0.html

though be forewarned it isn't perfect. There's an exception safety bug
in vector_base. But the general idea is correct and good.

The notion and use of operator overloading is introduced very early in
Accelerated C++, in section 1.2. Examples of how to overload operators
are in section 11.2 "Defining Abstract Data Types". There is an example
Vec<Twith an operator[](size_type). I'm not positive if this is the
first such example in the book or not.

-Howard
Nov 27 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Tony Johansson | last post by:
Hello! I'm reading in a book about C++ and that is something that sound strange. It says "Pointers have reference-assignment semantics similar to those in Java. For example, after the...
2
by: Alex | last post by:
Entering the following in the Python shell yields >>> help(dict.copy) Help on method_descriptor: copy(...) D.copy() -> a shallow copy of D >>>
4
by: fperfect13 | last post by:
Hi, I wanted to perform a deep copy of an array. Searching on google I ran into different opinions : C# Interview Questions (http://blogs.wwwcoder.com/tsvmadhav/archive/2005/04/08/2882.aspx)...
2
by: bonk | last post by:
I have come across the need to distinguish between the creation of a deep and a shallow copy and with great interest I have read this article: ...
26
by: saxenavaibhav17 | last post by:
what is Deep Copy, Shallow copy and Bitwise copy, Memberwise copy? and what is the difference between them? pls help vaibhav
13
by: blangela | last post by:
I have decided (see earlier post) to paste my Word doc here so that it will be simpler for people to provide feedback (by directly inserting their comments in the post). I will post it in 3 parts...
1
by: blangela | last post by:
3.0 Advanced Topic Addendum There are a few cases where the C++ compiler cannot provide an overloaded assignment operator for your class. If your class contains a const member or/and a...
4
by: shuisheng | last post by:
Dear All, Is there any easy way to make sure all my object copies are deep copy or shallow copy? I do not like to implement it in each class one by one. Thanks, Shuisheng
3
by: raylopez99 | last post by:
The "C# Cookbook" (O'Reilly / Jay Hilyard), section 3.26, is on deep cloning versus shallow cloning. The scanned pages of this book are found here: http://www.sendspace.com/file/mjyocg (Word...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.