Idea for future version of C#: Move semantics for structs

  • Thread starter Thread starter Samuel Barber
  • Start date Start date
S

Samuel Barber

Consider a struct that resembles this:

struct mystruct
{
byte[] myarray;
// ...other stuff...
}

i.e. a struct that contains at least one reference/pointer.

The meaning of "=" (and the meaning of by-value parameter passing) is
to perform a memberwise copy of the struct. This is also known as a
"shallow copy", because it doesn't copy heap data (myarray in the
example above).

This behavior is hazardous, because a shallow copy isn't really an
object copy (clone). The objects can get into an inconsistent state,
unless they are read-only.

What is desired is for the source object to be "destroyed" when a copy
is done, so that a copy leaves only one usable object - making it a
safe move operation, as opposed to a dangerous copy. This can be
accomplished by simply zeroing/nulling the members of the source
object after the copy. (In the case where the compiler can determine
statically that the source object is never used again, the zeroing can
be optimized away).

Some people might think, "What's the point? Just use a class." But
structs will be more useful in C#2.0 than they are now, because you'll
be able to store them directly in collections (no boxing).

I'd like to be able to say something like:
move struct mystruct {....}

and get the move semantics described above.

Sam
 
Samuel,

I don't think that this is needed, to be honest. While I respect the
use situation that you have presented, I think that it is not that common to
introduce a new language element.

Also, I think that proper design would solve this. What you are
describing is easily solved by the singleton pattern, IMO.

Hope this helps.
 
Nicholas Paldino said:
Also, I think that proper design would solve this. What you are
describing is easily solved by the singleton pattern, IMO.

I'm afraid I didn't communicate well, since "singleton pattern" is
completely unrelated. The intent of nulling source objects (when a
memberwise copy is performed) is not to limit the number of instances
(it doesn't do that), but rather to make it safer to use structs with
reference members. There is no way to implement it in the language,
because C# gives no control over object copying.

Sam
 
Back
Top