Why can't I init a new var from const var?

Random D user via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 11 15:15:31 PST 2017


I can init a variable from mutable source without defining any 
constructor or assignment operators, but not if the source is 
const. I would imagine the behavior to be the same with mutable 
and const source, since it's just reading the source and copying 
it.

Is there a reason for this? Or is this a bug?
I can workaround this by making copies or casting, that just 
creates ugly code everywhere.

Here's an example (with dmd 2.073):

struct Foo
{
     this( Foo source )
     {
         buf = source.buf.dup;
     }

     this( const Foo source )
     {
         buf = source.buf.dup;
     }

     this( const ref Foo source )
     {
         buf = source.buf.dup;
     }

     void opAssign( Foo source )
     {
         buf = source.buf.dup;
     }

     void opAssign( const Foo source )
     {
         buf = source.buf.dup;
     }

     void opAssign( const ref Foo source )
     {
         buf = source.buf.dup;
     }

     char[] buf;
}

Foo fun(const ref Foo foo, Foo foo2)
{
     Foo bar  = foo;                     // Error: cannot 
implicitly convert expression (foo) of type const(Foo) to Foo
     Foo baz  = foo2;                    // Ok, No need for 
constructors or opAssign
     Foo baz2 = cast(const Foo)foo2;     // Error: cannot 
implicitly convert expression (Foo(null).this(foo2)) of type 
const(Foo) to Foo
     Foo bar2;
     bar2     = foo;                     // uses opAssing( const 
Foo ) / opAssign( const ref Foo )
     Foo bar3;
     bar3     = foo2;                    // uses opAssign( const 
Foo ) / opAssign( Foo )
     Foo bar4;
     bar4     = cast(const Foo)foo2;     // uses opAssing( const 
Foo )

     //Foo bar = Foo(foo);     // This works provided there is 
non-const opAssign defined.
     //Foo bar = cast(Foo)foo; // This seems to work as well
     return bar;
}

Foo foo;
foo = fun(foo, foo);



More information about the Digitalmars-d-learn mailing list