Constructors (starstruck noob from C++)

Robert Jacques sandford at jhu.edu
Thu Jan 20 21:28:39 PST 2011


On Thu, 20 Jan 2011 22:02:42 -0500, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> On 1/20/11 7:18 PM, Luke J. West wrote:
>> Hi to all from a total noob.
>>
>> first of all, I'd like to say how impressed I am with D. In fact, I keep
>> pinching myself. Have I *really* found a language worth leaving C++ for
>> after two decades? It's beginning to look that way. Obviously I'm
>> devouring the 2.0 documentation right now, but have not yet found out
>> how to create a new instance of an existing class object. What I mean
>> is, given...
>>
>> auto a = new A;
>>
>> how do I, in c++ speak, do the D for...
>>
>> A  b(a); // or if you prefer...
>> A* b = new A(a);
>>
>> I'm sure this must be trivial.
>>
>> Many many thanks,
>>
>> Luke
>
> Hopefully this won't mark a demise of your newfound interest :o). If A  
> were a struct, auto b = new A(*a) would do. For classes, D does not  
> provide automatic copy constructors; you need to define and follow a  
> sort of cloning protocol.
>
> That being said, it's not difficult to define a generic function that  
> copies fields over from one class object to another. Here's a start:
>
> import std.stdio;
>
> void copyMembers(A)(A src, A tgt) if (is(A == class)) {
>      foreach (e; __traits(allMembers, A)) {
>          static if (!is(typeof(__traits(getMember, src, e)) == function)
>                     && e != "Monitor")
>          {
>              __traits(getMember, tgt, e) = __traits(getMember, src, e);
>          }
>      }
> }
>
> class A {
>      int x = 42;
>      string y = "hello";
>      final void fun1() {}
>      void fun2() {}
>      static void fun3(){}
> }
>
> void main() {
>      auto a = new A;
>      a.x = 43;
>      auto b = new A;
>      copyMembers(a, b);
>      assert(b.x == 43);
> }
>
> I think copyMembers belongs to the standard library. I wanted to define  
> a family of functions like it but never got around to it.
>
>
> Andrei

First, why not use tupleof? b.tupleof = a.tupleof; works perfectly fine,  
simpler and ahem, actually works. __traits(getMember, ...) has to obey  
scoping rules, so using it with a class that defines private variables  
results in a message like class hello.A member x is not accessible.  
Furthermore, you need to filter allMembers by a lot more than just  
function and "Monitor" as it also includes enum constants, etc. Having  
tried using it for serialization, I know it's non-trivial to use  
correctly, if you only want the actual data fields.

i.e.

void copyMembers(A)(A src, A tgt) if (is(A == class)) { tgt.tupleof =  
src.tupleof; }


More information about the Digitalmars-d mailing list