473,698 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copy ctore, assignment operator and Clone() - dang!

I can't find a straight answer on what to use? I need a deep copy, so I
implemented IConeable and the Clone() method. However, I'm not sure I did
it correct. Is it suposed to be an allocation of a new object, then the
assignment of each member? Is that all or is there something else I need to
do?

Here is my code
<code>
public Object Clone()
{
BOLDeviceProtoc ol newObject = new BOLDeviceProtoc ol();

newObject.m_cus tom = this.m_custom;
newObject.m_dal = this.m_dal;
newObject.m_dev iceProtocolID = this.m_devicePr otocolID;
newObject.m_dev iceSettingsID = this.m_deviceSe ttingsID;
newObject.m_dur ation = this.m_duration ;
newObject.m_ena bled = this.m_enabled;
newObject.m_isD irty = this.m_isDirty;
newObject.m_pro tocolID = this.m_protocol ID;
newObject.m_pro tocolName = this.m_protocol Name;
newObject.m_pro tocolNumber = this.m_protocol Number;
newObject.m_seg ments = new BOLProtocolSegm entList();
foreach(BOLProt ocolSegment segment in this.m_segments )
{
newObject.m_seg ments.Add(segme nt);
}

return newObject;
}
</code>

How do I know that m_segments.Add( ) is creating a deep copy of segment?

I'm just looking for a little verification.

Thanks,
Steve
Nov 17 '05 #1
6 2147
That depends upon the implementation of BOLProtocolSegm entList. If
BOLProtocolSegm entList.Add is defined to clone the object before adding
the clone to the list, then yes, your Clone() method is cloning the
segments because it's calling the Add() method, which is designed to
clone before it adds.

However, that's a really bad design.

More likely (and more correctly), the Add method of
BOLProtocolSegm entList should not clone before it adds. It should just
add whatever it's given to the list. In that case, you have to do the
Clone yourself, if you want a deep copy:

newObject.m_seg ments.Add(segme nt.Clone());

and yes, this means that BOLProtocolSegm ent must implement ICloneable,
too.

Nov 17 '05 #2

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** *************@g 43g2000cwa.goog legroups.com...
That depends upon the implementation of BOLProtocolSegm entList. If
BOLProtocolSegm entList.Add is defined to clone the object before adding
the clone to the list, then yes, your Clone() method is cloning the
segments because it's calling the Add() method, which is designed to
clone before it adds.

However, that's a really bad design.

More likely (and more correctly), the Add method of
BOLProtocolSegm entList should not clone before it adds. It should just
add whatever it's given to the list. In that case, you have to do the
Clone yourself, if you want a deep copy:

newObject.m_seg ments.Add(segme nt.Clone());

and yes, this means that BOLProtocolSegm ent must implement ICloneable,
too.


Thank you for the response, Bruce. It's taking a little time to get my head
around the details for reference/value types. It was really nice and easy
when I didn't care, but now that I need to worry about it, it's a little
confusing.

What I have done for some of my objects is implement Clone() like this:
<code>
public Object Clone()
{
BOLCustomerConf iguration newConfig =
(BOLCustomerCon figuration)this .MemberwiseClon e();

// deep copy reference types
newConfig.m_dal = new DALMSAccess();
newConfig.m_des cription = (string)this.m_ description.Clo ne();
newConfig.m_nam e = (string)this.m_ name.Clone();
newConfig.m_dev iceSettings = new BOLDeviceSettin gsList();
foreach(BOLDevi ceSettings item in this.m_deviceSe ttings)
{
newConfig.m_dev iceSettings.Add ( item );
}

return newConfig;
}
</code>

That seems correct to me and so far, it seems to behave correctly. String,
being an array and therefore a reference type needs a deep copy, correct?

Thanks again for the post,
Steve
Nov 17 '05 #3
No, string does not need a deep copy because string is a bit of an
oddity: it's immutable. That means that you can never change the
contents of a string, only generate a new string based on an existing
string. So, once you say:

string s = "Hello There!";
string a = s;

You can be guaranteed that the string that "a" refers to will always
say "Hello There!" unless you change "a". If you do this:

s = s.Substring(0, 5);

Then all you've done is assign "s" to refer to a different string that
contains "Hello". "a" will continue to refer to the original string,
which says "Hello There!".

So, yes, strings are reference types, but they are special reference
types that you can trust never to change.

Nov 17 '05 #4
Interesting, so for string, in my Clone() method I would simple need to do:
string newString = new string.empty();
newString = oldString;

Since there is not a constructor that will take string, I guess this is the
cleanest way?
"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
No, string does not need a deep copy because string is a bit of an
oddity: it's immutable. That means that you can never change the
contents of a string, only generate a new string based on an existing
string. So, once you say:

string s = "Hello There!";
string a = s;

You can be guaranteed that the string that "a" refers to will always
say "Hello There!" unless you change "a". If you do this:

s = s.Substring(0, 5);

Then all you've done is assign "s" to refer to a different string that
contains "Hello". "a" will continue to refer to the original string,
which says "Hello There!".

So, yes, strings are reference types, but they are special reference
types that you can trust never to change.

Nov 17 '05 #5
Not even. All you need to do is this:

<code>
newConfig.m_des cription = this.m_descript ion;
newConfig.m_nam e = this.m_name;
</code>

Since strings are immutable, you are guaranteed that the strings that
newConfig.m_des cription and newConfig.m_nam e refer to will never
change. The only way to "change them" is to point m_description and
m_name to some other strings.

Nov 17 '05 #6
Oh wow, this is pointing out a much bigger issue I'm having then ;)
I had weird behavior this morning where;
SettingsObject A.Name = "Default";
// create a copy of SettingsObject, B
B.Name = "Test";

was changing both values. I didn't check too into it, I just assumed they
were reference types and then changed the Clone() method, but based on your
post (and the test I just did), this would indicate that something very
different is happening (Like I didn't really create a copy of SettingsObject
but perhaps a reference)

OK, I'm done now, thanks for your help, I get it.


"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Not even. All you need to do is this:

<code>
newConfig.m_des cription = this.m_descript ion;
newConfig.m_nam e = this.m_name;
</code>

Since strings are immutable, you are guaranteed that the strings that
newConfig.m_des cription and newConfig.m_nam e refer to will never
change. The only way to "change them" is to point m_description and
m_name to some other strings.

Nov 17 '05 #7

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

Similar topics

42
5780
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
4
5429
by: Kevin | last post by:
Hi all, I've got a PHP4 app that I developed which I'm trying to get to run on a PHP5 server. Everything works great, except for one thing. There's a particular routine that creates an original object, then copies it. (The object constructor gets some meta information from the database, so I copy it for performance reasons). The routine then modifies the copies. PHP5 copies by reference by default, so this doesn't work--- I'm not
14
2716
by: Arne | last post by:
In C++ we have a copy constructor. What is the equivalent in .Net? Would that be a clone method?
1
1478
by: miben | last post by:
I want to create a new inherited class givin its base. For example: class Base { public: void operator =(const Base &base) { // copy base items } }; class Inherits: public Base {
17
3566
by: baibaichen | last post by:
i have written some code to verify how to disable slicing copy according C++ Gotchas item 30 the follow is my class hierarchy, and note that B is abstract class!! class B { public: explicit B(INT32 i =0):i_(i){} virtual ~B(){}
2
3087
by: gyarnell | last post by:
Just ran into a problem upgrading from GCC 2.96 to GCC 3.3.2. There is a bug somewhere, could be in 2.96, could be in 3.3.2, could be in the code I'm compiling. Here's a minimal example class A { public: virtual int f() = 0; private: int a; };
11
3430
by: Nindi73 | last post by:
A few days a ago I posted my code for a deep copy pointer which doesn't require the pointee object to have a virtual copy constructor. I need help with checking that it was exception safe and exception neutral/ I got a reply from Bux with his code for a smart pointer with far fewer lines of code and more cleaner design, not over engineered like mine. ...
5
2096
by: raylopez99 | last post by:
In C++, you have symbolic overriding of "+", "=", etc, which C# also has. This question is not really about that. Rather, in C#, when you say: MyObject X = new MyObject(); MyObject Y = new MyObject(); X = Y; //what does this '=' mean?
2
1270
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians! I have, perhaps, a simple question regarding deep copy and the assignment operator. I'm creating a class, and I would like to perform a deep copy of all the members in an instance of the class. I know I can derive the class from ICloneable and override the Clone() function. I do this, and I can accurately create a deep copy of my class. MyClass c1 = new MyClass(...); MyClass c2;
0
9170
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8904
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7741
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.