References in D
Maxim Fomin
maxim at maxim-fomin.ru
Sat Sep 15 07:06:38 PDT 2012
On Saturday, 15 September 2012 at 13:49:02 UTC, Simen Kjaeraas
wrote:
>> void foo(ref S s); // cannot pass null pointer S* or null -
>> "always there"
>
> void bar( ref int n ) {
> n = 3;
> }
>
> void main( ) {
> int* p = null;
> bar( *p );
> }
>
> Good luck.
>
> Of course, it's not that obvious in production code, but I've
> had this
> happen to me in C++, and - obviously - it can happen in D, too.
The problem happens because you deliberately passed hidden null
pointer. And in real code it could crash after dereferencing and
before passing to bar, if accessed (meaning that problem is in
erroneous pointer usage, not accepting ints through reference in
bar). Certainly, it is possible to break even in such cases, as
well as in other parts of the language which doesn't necessarily
mean that such parts of the language are broken. What I was
talking about is:
void bar( ref int n ) {
n = 3;
}
void main( ) {
int* p = null;
bar(p); // error
bar(null); //error
}
More information about the Digitalmars-d
mailing list