473,545 Members | 1,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deep versus Shallow Copy - Part 3

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 reference member, the compiler will not be able
to synthesize an assignment operator for your class. It actually helps
to think of a reference member as a const member (since it cannot be
made to reference any other object once it has been initialized).

Interestingly, the compiler will be able to synthesize a copy
constructor for a class that defines a const member or a reference
member, but the compiler supplied copy constructor will do a shallow
copy of any reference members that are defined for the class.

In the case where your class contains a reference member, you will
likely want to overload the assignment operator for your class (since
the compiler cannot do it for you).

Here is some sample code:

class ABC // dummy class used below
{};

class Example3
{
public:
Example3(ABC &); // ctor (this class has no default ctor)
Example3( const Example3 &); // copy ctor
Example3 & operator = (const Example3 &); // overloaded
// assignment operator
private:
int ii;
double dd;
ABC & abcRef; // will be made to reference an ABC object
// in the ctor MIL
const long Cll; // must be init. in ctor MIL
};
// ctor - Note: both abcRef must be init. in the MIL,
// just as a const member would need to be
Example3::Examp le3(ABC & abcObj)
: abcRef(abcObj), Cll(1234567890)
{
ii = 10; // assign some value
dd = 3.765; // assign some value
}
// copy ctor - compiler supplied copy ctor would do the same
Example3::Examp le3(const Example3 & src)
:ii(src.ii), dd(src.dd), abcRef(src.abcR ef), Cll(src.Cll)// MIL
{}
// overloaded assignement operator
Example3 & Example3::opera tor = (const Example3 & RHS)
{
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

abcRef = RHS.abcRef; // this does a deep copy!!!
// Cll = RHS.Cll; We cannot do this, since Cll is const

return *this; // return the modified LHS operand.
}
}

// Simple program to test our Example3 class
int main()
{
ABC abc_1,abc_2; // Create 2 ABC objects

Example3 ex2_1(abc_1), ex2_2(abc_2);// Will invoke ctor (twice).

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

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

return 0; // We are finished!

} // end of main()

The overloaded assignment operator for the Example3 class above does a
deep copy of the reference member. It cannot do anything with the Cll
member since Cll is const.

The copy constructor for the Example3 class must of course do a shallow
copy of the reference member, since we have not provided the copy
constructor with any other ABC object that the newly created abcRef
member could be made to reference. We are able to copy the const
member in this case since the newly created const member has yet to be
initialized. As hinted in the code comments above, the copy
constructor supplied above is not necessary, since the synthesized copy
constructor will effectively do exactly the same thing.

If you would like to read further discussion of the Rule of Three, read
the following on-line article (Warning: includes features of the C++
language not discussed in this course):

http://www.artima.com/cppsource/bigtwo.html

Nov 26 '06 #1
1 2111
* blangela:
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 reference member, the compiler will not be able
to synthesize an assignment operator for your class. It actually helps
to think of a reference member as a const member (since it cannot be
made to reference any other object once it has been initialized).

Interestingly, the compiler will be able to synthesize a copy
constructor for a class that defines a const member or a reference
member, but the compiler supplied copy constructor will do a shallow
copy of any reference members that are defined for the class.

In the case where your class contains a reference member, you will
likely want to overload the assignment operator for your class (since
the compiler cannot do it for you).
No, I will not likely want to overload the assignment operator.

The idea that assignment "must" be provided for every class is an
unfortunate misunderstandin g that is the cause of an inordinate number
of man-years of maintenance work, because it really messes things up.

Teach your students about the difference between a class meant to be
copyable, and a class meant to be non-copyable -- and don't do that as
an "advanced" topic, because it's really a /fundamental/ topic.

It's generally a good idea to limit a non-copyable class (e.g. a Windows
class) to dynamic allocation, so that it will not pass compilation to
declare an automatic variable, static variable or member of that class.
That can be achieved by limiting access to constructors (with factory
functions provided) or the destructor (no factory functions needed). I
favor the destructor, but unfortunately it's not yet in the FAQ.

There is a discussion of this and associated techniques in <url:
http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf>.

Hth.,

- Alf

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 27 '06 #2

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

Similar topics

5
3267
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 assignment Student* john = michael; both john and michael share the same object. This type of an assignment is different then value-assignmnet semantics...
2
12340
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
52285
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) 10.What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
2
10093
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: http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx This artivle seems to hint that I should not use System.IClonable but instead define my own interface(s) for cloning. Now since this...
26
15773
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
4988
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 to make it more manageable. Below is a draft of a document that I plan to give to my introductory C++ class. Please note that I have purposely...
9
1661
by: blangela | last post by:
2.0 Sample Code class ABC // dummy class used below {}; class Example2 { public: Example2(); // default ctor Example2( const Example2 &); // copy ctor
4
3134
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
8741
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 format, 3 pp) My question, coming from a C++ background where deep copying is done, is why in C# you would do either deep or shallow copying as...
0
7401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7807
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7756
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1879
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1014
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
703
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.