Const struct syntax
Timon Gehr
timon.gehr at gmx.ch
Tue Aug 30 04:44:57 PDT 2011
On 08/30/2011 01:19 PM, Jonathan M Davis wrote:
> On Tuesday, August 30, 2011 07:08:32 bearophile wrote:
>> DMD 2.055head gives no compile-time errors on this, is this expected and
>> good/acceptable?
>>
>>
>> struct Foo {
>> int x;
>> this(int x_) { this.x = x_; }
>> }
>> void main() {
>> auto f1 = new const(Foo)(1);
>> f1.x++;
>> auto f2 = new immutable(Foo)(1);
>> f2.x++;
>> auto f3 = const(Foo)(1);
>> f3.x++;
>> auto f4 = immutable(Foo)(1);
>> f4.x++;
>> }
>
> I believe that that's as expected. If the struct had member variables which
> were references or pointers, then you'd need an immutable constructor to
> construct an immutable one, but in this case, it shouldn't be necessary. And I
> don't think that it's ever necessary to have a special constructor for const.
>
> - Jonathan M Davis
The problem is that:
struct Foo {
int x;
this(int x_) { this.x = x_; }
}
static assert(is(typeof(new const(Foo)(1)) == Foo*));
static assert(is(typeof(new immutable(Foo)(1)) == Foo*));
static assert(is(typeof(const(Foo)(1)) == Foo));
static assert(is(typeof(immutable(Foo)(1)) == Foo));
// But:
struct Bar {
int x;
}
static assert(is(typeof(new const(Bar)) == const(Bar)*));
static assert(is(typeof(new immutable(Bar)) == immutable(Bar)*));
static assert(is(typeof(const(Bar)(1)) == const(Bar)));
static assert(is(typeof(immutable(Bar)(1)) == immutable(Bar)));
And I'd call that a bug.
More information about the Digitalmars-d-learn
mailing list