inout constructor?

Stewart Gordon smjg_1998 at
Fri Jan 27 05:05:24 PST 2012

On 26/01/2012 15:27, Steven Schveighoffer wrote:
> auto tsm = TestStruct(&xm);
> auto tsc = TestStruct(&xc);
> auto tsi = TestStruct(&xi);
> writeln(typeof(tsm).stringof); // TestStruct
> writeln(typeof(tsc).stringof); // const(TestStruct)
> writeln(typeof(tsi).stringof); // immutable(TestStruct)

To actually get an immutable object (trying it on DMD 2.057), you need to use

     auto tsi = immutable(TestStruct)(&xi);

I think the reason is: Think of a constructor as a method that always returns this.  The 
implicit this pointer points to a space that has been allocated in advance to hold the 
constructed object.

     this(inout(int)* d) inout { = d;

     auto ts = TestStruct(&xi);

is essentially

     inout(TestStruct) ctor(inout(int)* d) inout { = d;
         return this;

     TestStruct temp;
     auto ts = temp.ctor(&xi);

The implicit this pointer is a TestStruct* (mutable), but &xi is an immutable(int*).  The 
only way to match both is to match the inout as const, so a const is what it returns.

But it doesn't work properly with a class instead of a struct at the moment.

> I'll note that I don't think this is currently supported, but I could see how it would be
> useful.

You away from your usual testing station?

> However, in that bug report, there are no inout parameters besides the 'this' pointer, so
> I'm not sure what the purpose would be there.

The purpose of it in the example is to be a minimal testcase for the bug.

But in the general case, the purpose is to enable a mutable, const or immutable object to 
be constructed to wrap existing data that has the same constancy.


More information about the Digitalmars-d-learn mailing list