Ref local variables?

Marco Leise Marco.Leise at gmx.de
Wed Jan 11 12:12:36 PST 2012


Am 11.01.2012, 14:27 Uhr, schrieb Steven Schveighoffer  
<schveiguy at yahoo.com>:

> On Tue, 10 Jan 2012 20:06:21 -0500, Ben Davis <entheh at cantab.net> wrote:
>
>> Hi,
>>
>> Please excuse the cross-post with D.learn. People have been helpful  
>> there with workarounds, but I'm bringing it here in the hope that we  
>> can discuss a language enhancement.
>>
>> So - could support for 'ref' local variables be added, or is there a  
>> reason not to?
>
> This has been requested in the past.  In order to convince Walter, it is  
> helpful to examine past failed arguments.  Try a search on the  
> newsgroups archive.
>
> You also have to show why it's better to do it via the language than via  
> the library.  I think Simen's solution in the D.learn thread is pretty  
> compelling.
>
> -Steve

Sorry, but it sounds plain masochistic to import a module and then  
instantiate a template every time you want quick access to variable in  
non-trivially indexed array. All I want is a pointer to that element, but  
if possible avoid the pointer syntax. Here is another example:

	Row* rt_a = &row_types[n_row_types];
	rt_a.pattern = pattern & MASK_HIGH_BIT;
	foreach (b, ref rt_b; row_types[0 .. n_row_types]) {
		if ((rt_a.pattern & rt_b.pattern) == 0) {
			rt_a.combinations ~= b;
			rt_b.combinations ~= n_row_types;
		}
	}
	++n_row_types;

Every solution proposed so far obfuscates and/or increases lines of code.  
I don't mind templates or alias this, I use them in other situations.  
Especially with the alias syntax (alias row_types[n_row_types] rt_a) I  
have the logical problem, that rt_a is just a macro, not the manifest  
pointer to the requested array slot. If I change n_row_types afterwards,  
rt_a changes. The other issue is that the OP has a more involved indexing  
scheme, that slows down the code if evaluated again and again.

Local ref variables on the other hand (if it doesn't break the language)  
are a way to use pointers without pointer syntax. That precludes any form  
of pointer arithmetics and unsafe operations that are generally connected  
to the idea of pointers on these variables. Especially in @safe code I  
would not want to resort to pointers, but write more in a Java style where  
everything is a reference.

Again, the problem is the lack of a clean, concise syntax to declare  
references to structs (either returned from a function as ref or retrieved  
 from an array). Or we just stick to pointers (that I manage to avoid  
everywhere else, but in this case).

- Marco


More information about the Digitalmars-d mailing list