Why can't we make reference variables?
Tommi
tommitissari at hotmail.com
Tue Aug 28 21:46:25 PDT 2012
On Wednesday, 29 August 2012 at 03:21:04 UTC, Jonathan M Davis
wrote:
>> >> > void main()
>> >> > {
>> >> >
>> >> > immutable(Test)* ptr = new immutable(Test);
>> >> > ptr.foo();
>> >> >
>> >> > }
>> >>
>> >> Now, that's a surprise for someone coming from C++. But even
>> >> though ptr looks like a reference variable in your example,
>> >> it
>> >
>> >> doesn't look like it at all in this example:
>> > I've been primarily a D guy for years, and even I'm surprised
>> > by that!
>> > O_O
>>
>> You didn't know that the dot operator does dereference? That's
>> quite a big one to miss for years.
>
> Yeah. I'm a bit confused about what's so suprising about that
> code.
>
> - Jonathan M Davis
The weird thing is that you can use a member access operator with
a pointer (without explicitly dereferencing the pointer first).
At least I didn't know what to expect the following code to print:
struct MyStruct
{
int _value = 0;
void increment()
{
++_value;
}
}
void increment(ref MyStruct* ptr)
{
++ptr;
}
void main()
{
MyStruct[2] twoStructs;
twoStructs[1]._value = 42;
MyStruct* ptrFirstStruct = &twoStructs[0];
// Are we incrementing the pointer using UFCS or
// are we calling the member function in MyStruct?
ptrFirstStruct.increment();
// This prints 1, so we called the actual method
writeln((*ptrFirstStruct)._value);
}
More information about the Digitalmars-d
mailing list