473,788 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What should function returning a reference return on failure?

I'm sure this has been asked a few times, but I'm still not sure.

I want to create a function to simplify getting a reference to a CMap in a
map.

This is what I do now in code:

std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
{
CMap& ThisMap = *((*ThisMapIt). second);
// Work with ThisMap
}

Now, the map number should always be in the map, but I'm a bit pedantic and
like to check for all possible errors. I'd like to create a function to do
this like:

CMap& FindMap( const unsigned int MapNumber )
{
std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
return *((*ThisMapIt). second);
else
// What to return here? A reference can't be null!
}

My alternative is to return a CMap* and return NULL on failure, but I would
rather deal with references so I can use . instead of ->

Any suggestions?

I guess I could return a CMap* and in code do:

CMap* MapP = FindMap( ThisPlayer.Char acter.Map );
if ( MapP != NULL )
{
CMap& ThisMap = *MapP;
// Work with ThisMap
}

if I really have to
May 8 '06 #1
21 2699

Jim Langston wrote:
I'm sure this has been asked a few times, but I'm still not sure.

I want to create a function to simplify getting a reference to a CMap in a
map.

This is what I do now in code:

std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
{
CMap& ThisMap = *((*ThisMapIt). second);
// Work with ThisMap
}

Now, the map number should always be in the map, but I'm a bit pedantic and
like to check for all possible errors. I'd like to create a function to do
this like:

CMap& FindMap( const unsigned int MapNumber )
{
std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
return *((*ThisMapIt). second);
else
// What to return here? A reference can't be null!
}

My alternative is to return a CMap* and return NULL on failure, but I would
rather deal with references so I can use . instead of ->

Any suggestions?

Throw an exception.

May 8 '06 #2
* Jim Langston:
I'm sure this has been asked a few times, but I'm still not sure.


If the function returns a reference, it's guaranteeing that if it
returns, the result is a valid reference.

You have the choice of using (1) a reference to some special object
denoting "no object" or "failure", or (2) throwing an exception.

(2) is most clean, most reliable wrt. client code checking, and may help
avoid constructing a large dummy object.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 8 '06 #3
On Mon, 08 May 2006 07:50:00 -0700, Jim Langston wrote:
I'm sure this has been asked a few times, but I'm still not sure.

I want to create a function to simplify getting a reference to a CMap in a
map.

This is what I do now in code:

std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
{
CMap& ThisMap = *((*ThisMapIt). second); // Work with ThisMap
}

Now, the map number should always be in the map, but I'm a bit pedantic
and like to check for all possible errors. I'd like to create a
function to do this like:

CMap& FindMap( const unsigned int MapNumber ) {
std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
return *((*ThisMapIt). second);
else
// What to return here? A reference can't be null!
}

My alternative is to return a CMap* and return NULL on failure, but I
would rather deal with references so I can use . instead of ->

Any suggestions?

I guess I could return a CMap* and in code do:

CMap* MapP = FindMap( ThisPlayer.Char acter.Map ); if ( MapP != NULL ) {
CMap& ThisMap = *MapP;
// Work with ThisMap
}

if I really have to


That's one of your choices. There are three ways that I can think of:

1) Return a pointer and check for NULL.
2) Throw an exception and catch it somewhere
3) Return a reference to a "NULL CMap", that is a special instance of your
CMap object representing that no map exists.
May 8 '06 #4

"Alf P. Steinbach" <al***@start.no > wrote in message
news:4c******** *****@individua l.net...
* Jim Langston:
I'm sure this has been asked a few times, but I'm still not sure.


If the function returns a reference, it's guaranteeing that if it returns,
the result is a valid reference.

You have the choice of using (1) a reference to some special object
denoting "no object" or "failure", or (2) throwing an exception.

(2) is most clean, most reliable wrt. client code checking, and may help
avoid constructing a large dummy object.


I generally only like throwing exceptions on genuine errors, but you know
what? Not finding the CMap in the map is a genuine error, because it should
be there.

Thanks! I'll do that.
May 8 '06 #5
In article <yU***********@ fe05.lga>,
"Jim Langston" <ta*******@rock etmail.com> wrote:
Now, the map number should always be in the map, but I'm a bit pedantic and
like to check for all possible errors. I'd like to create a function to do
this like:

CMap& FindMap( const unsigned int MapNumber )
{
std::map<unsign ed int, CMap*>::iterato r ThisMapIt = World.Maps.find (
ThisPlayer.Char acter.Map );
if ( ThisMapIt != World.Maps.end( ) )
return *((*ThisMapIt). second);
else
// What to return here? A reference can't be null!
}

My alternative is to return a CMap* and return NULL on failure, but I would
rather deal with references so I can use . instead of ->

Any suggestions?


One school of thought is that if the missing map represents a run time
failure that you're anticipating (lack of memory, full disk, bad user
input, etc.) then an exception is appropriate. However if the missing
map represents a programming error, an assert may be more appropriate.

Of course for programs that must keep running no matter what, an assert
is rarely appropriate.

If you throw an exception, will you know what to do with it when you
catch it? If you can correct the error on catch, then an exception
sounds like the way to go. If on catch you're just going to say "I've
got a bug" and terminate, then an assert might actually help you find
the error earlier because it will be reporting it earlier (before stack
unwinding).

-Howard
May 8 '06 #6
Jim Langston wrote:
I generally only like throwing exceptions on genuine errors, but you know
what? Not finding the CMap in the map is a genuine error, because it
should be there.


If it's a _programmer_ error, put assert(false) at the bottom of the
function.

If it's an unpreventable _user_ error, throw. (So also throw if that
assert(false) gets optimized away. And pick a better argument than false.)

To finish Andre's list:

4) pass an optional sentinel object into FindMap, and return that.

If the caller passes no sentinel, construct the NullObject one and return
it:

CMap& FindMap(
const unsigned int MapNumber,
CMap const & sentinel = NullMap() );

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 8 '06 #7
> 4) pass an optional sentinel object into FindMap, and return that.

If the caller passes no sentinel, construct the NullObject one and return
it:

CMap& FindMap(
const unsigned int MapNumber,
CMap const & sentinel = NullMap() );


Oh, my. That's not const-correct. What's the fix?

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 8 '06 #8

"Alf P. Steinbach" <al***@start.no > wrote in message
news:4c******** *****@individua l.net...
* Jim Langston:
I'm sure this has been asked a few times, but I'm still not sure.


If the function returns a reference, it's guaranteeing that if it returns,
the result is a valid reference.

You have the choice of using (1) a reference to some special object
denoting "no object" or "failure", or (2) throwing an exception.

(2) is most clean, most reliable wrt. client code checking, and may help
avoid constructing a large dummy object.


Dang, there's one problem with the try...catch.

try
{
CMap& ThisMap = FindMap( MapNumber );
}
catch ( int )
{
LogError("Could not find map");
}

That ThisMap is only going to exist during the lifetime of the try block.
And I can't create it outside the block because it's a reference and has to
be initialized.

Now this means I'll have to put whole blocks of code inside the try block,
but I don't want to catch errors in a block for all the code, and a lot of
the code should execute anyway even if they can't find the map.

That is, this code won't compile:

int i = 1;
try
{
int& j = i;
}
catch (...)
{
}

std::cout << j << std::endl;
May 8 '06 #9
* Phlip:
4) pass an optional sentinel object into FindMap, and return that.

If the caller passes no sentinel, construct the NullObject one and return
it:

CMap& FindMap(
const unsigned int MapNumber,
CMap const & sentinel = NullMap() );


Oh, my. That's not const-correct. What's the fix?


Leave out the 'const'.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
14034
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return value of a function acts like 'by Val' returning the value only (except for objects) can you make it return a reference instead? cheers, Krackers
1
6180
by: Robert Oschler | last post by:
I have a "child" document that I use for an IFRAME element that I put into several "parent" documents. These "parent" documents therefore contain the IFRAME whose SRC property is set to the "child" document. The parent(s) have three Javascript functions, here they are: // ============================= var gMargin = 5;
12
3294
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
39
6555
by: Randell D. | last post by:
Folks, I'm sure this can be done legally, and not thru tricks of the trade - I hope someone can help. I'm writing a 'tool' (a function) which can be used generically in any of my projects. When it completes, it can call a success, or a failure function. The names of these success, or failure functions will differ, and I'd like to know how I can pass the name of a function to my tool, and how my tool can call the function, using that...
42
3171
by: Martin Jørgensen | last post by:
Hi, I'm trying to move a matlab program into c language. For those who knows matlab, this is the line I want to program in c: hx(1:nx,1:ny) = 0; % nx=10, ny=10 It works on a 2-dimensional array (size is 10*10), setting all the values inside the 10*10 matrix to zero. My C-function looks like this:
48
3382
by: Frederick Gotham | last post by:
The "toupper" function takes an int as an argument. That's not too irrational given that a character literal is of type "int" in C. (Although why it isn't of type "char" escapes me... ) The "toupper" function imposes a further constrait in that the value passed to it must be representable as a unsigned char. (If C does not require all character values to be positive, then again, this constrait too escapes me... ) Let's say we have the...
6
2590
by: Matthew Cook | last post by:
I would like to overload the unary minus operator so that I can negate an instance of a class and pass that instance to a function without creating an explicit temporary variable. Here is an example: #include <iostream> using namespace std; class Object { public:
8
2069
by: watkinsdev | last post by:
Hi, I have created a mesh class in visual studio 6.0 c++. I can create a device, render objects and can edit the objects by for instancnce selecting a cluster of vertices and processing the vertices and can do this multiple times on a sinlge vertex cluster. The problem I have been encoutering is that, if I select a second vertex cluster and try to edit that , the program crashes.
16
3450
by: John Doe | last post by:
Hi, I wrote a small class to enumerate available networks on a smartphone : class CNetwork { public: CNetwork() {}; CNetwork(CString& netName, GUID netguid): _netname(netName), _netguid(netguid) {}
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10173
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.