NULL reference..

Started by
12 comments, last by robinei 20 years, 3 months ago
When a function is supposed to return a reference to an object and something goes wrong, is there something one can do that is equivalent to returning NULL when dealing with pointers?
Advertisement
AFAIK just return NULL. NULL isn''t specific to pointers, it''s just the 0 address.
[size="1"]
NULL references are evil . Either return it as a pointer since so that the caller must check for its validity or throw an exception (there are a couple "std" exception types that might be what you want to use, or a custom "library" exception of some variety) unless you have a non-return value way of flagging an error.

To do that I guess at least som heavy casting would be required.

Just returning NULL I get this:

mapview.cpp:35: could not convert `0'' to `Map::Cell&''
Well I might just use pointers then... But it feels so much cleaner to use references :-)

And I''ve never really used exception handling before. It just feels unnecessary.
use a nullobject

or don''t use nulls to indicate errors, throw an exception instead
The obvious (and correct) answer is to throw an exception.
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
Perhaps it''s time to begin learning good coding practices.
References must always reference an object, if you have the situation where you might need to return NULL then use return a pointer instead of a reference as has been mentined and let the caller determine is the pointer is valid

My 2D game engine
Could you explicitly cast the NULL? Something like
return *(Cell**)(&NULL). I''m not sure, so don''t quote me on it, but I think you should be able to ::Somehow:: cast it to your type.

This topic is closed to new replies.

Advertisement