What should function returning a reference return on failure?

W

werasm

Phlip said:
5) return an iterator, and check if that == .end().


CMap & found = FindMap(2);

Now found refers to the temporary NullMap(), which destructed somewhere
around ;.

Should not work - cannot bind an rvalue (temporary) to a non-constant
reference. I know it compiles under MS VC++ 7.1, but that is erroneous.
This leaves you with this option (or an exception):
....
{
std::map<unsigned int, CMap*>::iterator ThisMapIt =
World.Maps.find( ThisPlayer.Character.Map );

if ( ThisMapIt != World.Maps.end() )
{
return *((*ThisMapIt).second);
}
else
{
//Same base type as CMap, but you know that!
static NullMap sentinal;
return sentinal;
}
}
 
W

werasm

Jim said:
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.
CMap& FindMap( const unsigned int MapNumber )
{
std::map<unsigned int, CMap*>::iterator ThisMapIt = World.Maps.find(
ThisPlayer.Character.Map );
if ( ThisMapIt != World.Maps.end() )
return *((*ThisMapIt).second);
else
// What to return here? A reference can't be null!
}

Instead of you map containing CMap*, I would consider using a map of
type:
std::map<unsigned int, boost::shared_ptr<CMap> >

FindMap could then return boost::shared_ptr or boost::weak_ptr. The
advantange of this is that the client can store the pointer if he needs
to. He can't use the pointer if invalid (or at least him using it will
cause visible problems). He could also test for validity of the
returned value (No sentinal required). This he could of course do using
normal pointers too (returning NULL), but who's to say the map doesn't
change after finding the item, or who's to say the client doesn't
decide to store the map entry for some reason. I like weak_ptr in this
case because one doesn't want the item to exist after being removed
from the map which weak_ptr enforces, but shared_ptr does not..

Regards,

W
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top