Why doesn't .NET CLI provide synthesized copy constructors and assignment operators for reference classes?

301 views Asked by At

I am writing a simple GUI using Visual C++ in the .NET framework and I am curious why there are no synthesized copy constructors or assignment operators for reference classes?

Basically, I started a Windows Form Application in Visual Studio and have my own data structure of parameters. But, I need instances of it (and pointers to instances of it) in my MainForm class and since the latter is a reference class I had to make my struct reference too.

1

There are 1 answers

2
IdeaHat On BEST ANSWER

So the long and short of it is because C++CLI is a .NET language, which is a reference based language (garbage collected, but the two are indistinguishable in this case). Almost everything default to a reference, meaning that all instances are accessed via handles, so in

Foo^ a = gcnew Foo(); Foo^ b = a;

a and b point to the same object. This is also true for other reference-defualting languages like Java.

The side effect of this is, unlike C++, nobody "owns" the instance pointed to by a. The actual lifetime of a is simply longer than all the handles. This makes making a default copy constuctor impossible. Take the simple reference class:

ref class Foo
{
   Bar^ bar;
};

When we make the copy of Foo, the compiler has no way of knowing if Foo owns bar or not. Thus, it cannot decide whether or not to copy the handle (shallow copy) or instantiate a new Bar (deep copy). Thus, the designers of such language don't typically provide a default copy constructor.