Why can't we define re-assignable const reference variable?

Matti Niemenmaa see_signature at for.real.address
Sun Feb 17 12:45:33 PST 2008


Janice Caron wrote:
> On 17/02/2008, none <z at gg.com> wrote:
>> Since 'in C++, const C* p; // non-const pointer, const data' is allowed, why
>> cannot we have 'non-const reference, const data' in D?
> 
> Why not just substitute your C++ pointer with a D pointer?
> 
> If it's acceptable to use a pointer in C++, then use the same pointer in D.

The difference is that in C++, 'new C' results in a C*, whereas in D it results 
in a C. Assuming C is a class, that is.

So the C++ code "C* a = new C();" converts to the D code "C a = new C;".

Now what he wants is to convert the C++ "const C* b = a;" to D "??? b = a;" with 
the semantics that b can be reassigned but the data behind it is unchangeable.

I.e.:

class Foo { public: int x; };

int main() {
	Foo* a = new Foo();
	const Foo* b = a;
	/* here, G++ gives "error: assignment of data-member 'Foo::x' in read-only 
structure" */
	b->x = 1;
	delete a;
}

Would become what, exactly, in D? (Disclaimer: I honestly don't know, but that's 
what I think he's asking for.)

-- 
E-mail address: matti.niemenmaa+news, domain is iki (DOT) fi



More information about the Digitalmars-d mailing list