mutable reference > pointer

Nathan M. Swan nathanmswan at gmail.com
Wed Jun 6 20:16:18 PDT 2012


On Wednesday, 6 June 2012 at 11:45:34 UTC, Gor Gyolchanyan wrote:
> I had this idea for a long time now and was trying to find a 
> reason
> why it was a bad idea.
> I failed to find that reason, so here it is:
>
> The idea is to have a mutable reference:
>
> int& a; // This is a mutable reference (essentially a pointer, 
> but
> with reversed behavior).
> assert(&a is null); // the address must be taken before
> address-related operations can be performed
> a = 20; // Access violation error due to null pointer 
> dereferencing.
> &a = new int; // Addresses, taken from mutable references are 
> lvalues.
> a = 20;
> assert(a == 20);
> &c = null;
> assert(&c is null);
>
> The idea here is to further reduce the need to explicitly deal 
> with
> addresses, while providing the number one reason why people use
> pointers: indirection.
> This mechanism will exclude indirection from the list of 
> reasons why
> one would use pointers.
> This is also good for reducing compiler magic, when dealing 
> with ref
> parameters and return types for functions.
> This mutable reference would be the complete compliment of 
> pointers:
> dereferencing a pointer yields a mutable reference, taking 
> address of
> a mutable reference yields a mutable pointer.
>
> This is not a proposition to add to D, but rather an idea, 
> which could
> eventually end up in D if you guys think it's worth it.
> It could also be used to remove the magic from reference types, 
> by
> adding their non-reference counter-parts and have their 
> "constructors"
> return such a mutable reference.

Here's a consideration: when I was a beginner learning C++ the 
difference between reference and pointer types (and their 
operators) confused me so much I avoided learning what pointers 
were for a long time:

type     create from t
T* ptr = &t
T& ref = t


More information about the Digitalmars-d mailing list