Newbie: copy, assignment of class instances

bearophile bearophileHUGS at lycos.com
Thu May 20 12:27:17 PDT 2010


Larry Luther:

>   class A {
>     int x, y;
>   }
> 
>   class B : A {
>     int z;
>   }
> 
>   B
>     foo = new B,
>     bar = new B;
> 
>   scope B
>     alpha = new B;

Don't write code like this, it's not easy to write:

>   B
>     foo = new B,
>     bar = new B;

Write it this way:

B foo = new B,
B bar = new B;

Or this way:

auto foo = new B,
auto bar = new B;


> Q1:  How do I copy the member variables contributed by base class A
>      from "foo" to "bar"?
>      In C++:  (A &) bar = foo;

There is no standard way to do this. In general you don't need to copy classes or their contents, because they are on the heap and managed by the GC. If you want to copy their contents you have to add methods written by you that perform the copy you need.


> Q2:  How do I do a deepcopy of foo to bar?
>      In C++:  bar = foo;

In general you don't do it. There is no standard way to perform a deep copy. You can write your code to do it, but it's not easy to write. So far I have never had to perform a deep copy on D classes.

For structs take a look at postblit too:
http://www.digitalmars.com/d/2.0/struct.html#StructPostblit


> Q3:  Is the object "alpha" on the stack (per documentation)?

In this case with ldc and dmd alpha is on the stack, you can see also reading the produced asm. On the docs you can read the rules that must be satisfied for scoped classes to be really allocated on the stack.


> Q4:  What happens when I do "alpha = foo;"?
>      "printf( "%p\n", alpha);" indicates that the address of "alpha" has changed.

alpha is on the stack, but beside alpha on the stack there is also the reference to alpha. So such reference gets rewritten.
Generally in D it's not a good idea to reassign the reference to a scoped class (some months ago I have even suggested to turn this operation into a syntax error) because when the scope ends, the class referenced by the reference to alpha gets collected, so if you change such reference to something else, it is such something else that gets collected. I am not sure what happens here, but this can be a source of bad troubles. This is probably why Walter was thinking of removing the scope attribute for classes.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list