www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - immutable constructor and semantics of two construction syntaxes

reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
When immutable constructors are implemented, will there be a difference 
between the two syntaxes below?

struct MyStruct
{
     int i;

     // ... assume that MyStruct has both
     // mutable and immutable constructors ...
}

     auto s0 = immutable(MyStruct)("some parameter");

     immutable s1 = MyStruct("some parameter");

The former syntax constructs an immutable literal, so the type of s0 is 
deduced to be immutable.

The latter syntax constructs a mutable literal and blits it to the 
immutable s1.

Should the former syntax call the immutable constructor and the latter 
syntax call the mutable constructor?

Ali
Apr 13 2013
parent reply Timon Gehr <timon.gehr gmx.ch> writes:
On 04/14/2013 02:48 AM, Ali Çehreli wrote:
 When immutable constructors are implemented, will there be a difference
 between the two syntaxes below?

 struct MyStruct
 {
      int i;

      // ... assume that MyStruct has both
      // mutable and immutable constructors ...
 }

      auto s0 = immutable(MyStruct)("some parameter");

      immutable s1 = MyStruct("some parameter");

 The former syntax constructs an immutable literal, so the type of s0 is
 deduced to be immutable.

 The latter syntax constructs a mutable literal and blits it to the
 immutable s1.

 Should the former syntax call the immutable constructor and the latter
 syntax call the mutable constructor?

 Ali
I guess so. But it does not really make sense to declare an immutable constructor if the struct instances implicitly convert between mutable and immutable.
Apr 14 2013
parent "deadalnix" <deadalnix gmail.com> writes:
On Sunday, 14 April 2013 at 08:03:16 UTC, Timon Gehr wrote:
 On 04/14/2013 02:48 AM, Ali Çehreli wrote:
 When immutable constructors are implemented, will there be a 
 difference
 between the two syntaxes below?

 struct MyStruct
 {
     int i;

     // ... assume that MyStruct has both
     // mutable and immutable constructors ...
 }

     auto s0 = immutable(MyStruct)("some parameter");

     immutable s1 = MyStruct("some parameter");

 The former syntax constructs an immutable literal, so the type 
 of s0 is
 deduced to be immutable.

 The latter syntax constructs a mutable literal and blits it to 
 the
 immutable s1.

 Should the former syntax call the immutable constructor and 
 the latter
 syntax call the mutable constructor?

 Ali
I guess so. But it does not really make sense to declare an immutable constructor if the struct instances implicitly convert between mutable and immutable.
I was about to answer exactly the same. Note that s1 should fail is immutable => mutable conversion can't be done implicitly (if MyStruct contains references).
Apr 14 2013