Hi!
> When you use assignment with structs, it does a bitwise copy -
> literally just copies a chunk of memory. How could a copy constructor
> be more efficient than that?
By not copying all the fields or deep copying contained objects.
Thanks!
Atmapuri
Jeroen Mostert - 11 Feb 2008 19:08 GMT
Please leave in a record of who wrote what.
> Jon Skeet wrote:
>> When you use assignment with structs, it does a bitwise copy -
>> literally just copies a chunk of memory. How could a copy constructor
>> be more efficient than that?
>
> By not copying all the fields or deep copying contained objects.
If you need a deep copy, use a class and implement ICloneable. It's never
the default, so that's not an issue.
Not copying all the fields would run counter to the idea of a copy
constructor... Even if you wanted this for a legitimate reason, separately
copying fields would be slower than letting the framework do a single block
copy, unless the fields you want to skip are very large. In which case,
you've got a very odd struct that you probably shouldn't be "copying" in the
first place. Just create a new one explicitly and assign its fields
explicitly, so everybody knows what you're doing.
Note that a C# "copy constructor" is not at all comparable to the C++ copy
constructor. The latter is a part of the language, the former is just
another constructor (and not in any way special). In particular, assuming
'b' is of a type compatible with T, then
T a = b;
will never invoke any constructor in C#,
T a(b);
is a syntax error, and
T a = new T(b);
will not compile unless you've actually written a constructor that takes an
argument that's type-compatible with T.

Signature
J.
Jon Skeet [C# MVP] - 11 Feb 2008 19:29 GMT
> > When you use assignment with structs, it does a bitwise copy -
> > literally just copies a chunk of memory. How could a copy constructor
> > be more efficient than that?
>
> By not copying all the fields
That sounds like a very odd usage - and selected copying is likely to
be slower than just blitting.
> or deep copying contained objects.
What makes you think it performs deep copies at the moment?

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Ben Voigt [C++ MVP] - 11 Feb 2008 21:00 GMT
>>> When you use assignment with structs, it does a bitwise copy -
>>> literally just copies a chunk of memory. How could a copy
[quoted text clipped - 4 lines]
> That sounds like a very odd usage - and selected copying is likely to
> be slower than just blitting.
Especially since the non-selected fields have to be initialized to
something, C# objects aren't allowed to contain uninitialized data.
>> or deep copying contained objects.
>
> What makes you think it performs deep copies at the moment?