473,326 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

function returning reference to empty object

Dear All,
can someone clarify me how to return the reference to the empty object
in case of error?

_not working_ Example of what i'd like to do:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return MyClassData();
}

This compiles, but of course it returns invalid reference in the case
when I don't find any suitable data. It there a way how to use the
reference in such case??

I have just one solution in my mind: if I create class variable:

class MyClass {
public:
MyClass () : errorVariable() {};

private:
MyClassData errorVariable;
}
and then I modify function:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return errorVariable;
}

But I'm not sure whether I like the idea of creating additional variable
just as placeholder for something which doesn't really exist..
Is there another way?

thx
d.
May 16 '07 #1
18 3203
Dejfson wrote:
Dear All,
can someone clarify me how to return the reference to the empty object
in case of error?
throw.
_not working_ Example of what i'd like to do:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return MyClassData();
}

This compiles, but of course it returns invalid reference in the case
when I don't find any suitable data. It there a way how to use the
reference in such case??

I have just one solution in my mind: if I create class variable:

class MyClass {
public:
MyClass () : errorVariable() {};

private:
MyClassData errorVariable;
No need to make it non-static.
}
and then I modify function:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return errorVariable;
}

But I'm not sure whether I like the idea of creating additional
variable just as placeholder for something which doesn't really
exist..

Is there another way?
Your class can have a static instance of itself, something like

class MyClass {
public:
...
static MyClassData errorVariable;
};

....
MyClassData MyClass::errorVariable;
....

if (data are ok)
return data;
else
return errorVariable;

....
if (&returnValueFromFunction == &errorVariable)
But it's better to 'try-catch' and 'throw'.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 17 '07 #2
"Dejfson" <de*****@dejfson.orgwrote in message
news:46*********************@newsspool.solnet.ch.. .
Dear All,
can someone clarify me how to return the reference to the empty object in
case of error?

_not working_ Example of what i'd like to do:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return MyClassData();
}

This compiles, but of course it returns invalid reference in the case when
I don't find any suitable data. It there a way how to use the reference in
such case??

I have just one solution in my mind: if I create class variable:

class MyClass {
public:
MyClass () : errorVariable() {};

private:
MyClassData errorVariable;
}
and then I modify function:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return errorVariable;
}

But I'm not sure whether I like the idea of creating additional variable
just as placeholder for something which doesn't really exist..
Is there another way?
I used throw as thus:

CPlayer& FindPlayer( const SOCKET Socket )
{
// Get a reference in the map for this player
map_player::iterator it = World.ConnectedPlayers.find( Socket );
if ( it != World.ConnectedPlayers.end() )
return (*it).second;
else
throw 0;
}

which I use a number of ways (is a client logged in, get a reference,
etc...) A few examples of usage:

// Get a reference in the map for this player
try
{
// Just do it to see if it throws
FindPlayer( Socket );
}
catch ( int )
{
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, "<Message
not sent, please relog - Error has been logged>" );
World.MessageBuffer.push_back( LogError( "Unlogged in client
attempting to send message on socket " + jml::StrmConvert( Socket ) + " on
IP " + IP ) );
return 0;
}

===================

case MSG_REQUEST_PLAYER_INFO: // "PlayerID"
{
SOCKET PlayerID = jml::StrmConvert<SOCKET>(
StrMessage );

try
{
CPlayer& TargetPlayer = FindPlayer( PlayerID );
if ( ThisPlayer.Character.Map ==
TargetPlayer.Character.Map ) // Make sure on same map
{
SendMessageToPlayer( Socket,
MSG_CREATE_PLAYER_OBJECT, CreateCharMessage( TargetPlayer.Socket,
TargetPlayer.Character ) );
}
}
catch ( int )
{
}
}

break;

======================

case MSG_DESTROY_CLIENT:
{
try
{
CPlayer& ThisPlayer = FindPlayer( Socket );
PlayerLeft( ThisPlayer );
}
catch ( int )
{
World.MessageBuffer.push_back( "Unlogged in socket " +
jml::StrmConvert( Socket ) + " disconnected." );
}
}

break;
May 17 '07 #3
Dejfson wrote:
Dear All,
can someone clarify me how to return the reference to the empty object
in case of error?

_not working_ Example of what i'd like to do:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return MyClassData();
}

This compiles, but of course it returns invalid reference in the case
when I don't find any suitable data. It there a way how to use the
reference in such case??

I have just one solution in my mind: if I create class variable:

class MyClass {
public:
MyClass () : errorVariable() {};

private:
MyClassData errorVariable;
}
and then I modify function:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return errorVariable;
}

But I'm not sure whether I like the idea of creating additional variable
just as placeholder for something which doesn't really exist..
Is there another way?

thx
d.
Use a static variable inside the function

const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

static MyClassData errorVariable;
return errorVariable;
}

This should be safe enough since you are returning a const reference.

john
May 17 '07 #4

Dejfson a scris:
Dear All,
can someone clarify me how to return the reference to the empty object
in case of error?

_not working_ Example of what i'd like to do:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return MyClassData();
}

This compiles, but of course it returns invalid reference in the case
when I don't find any suitable data. It there a way how to use the
reference in such case??

I have just one solution in my mind: if I create class variable:

class MyClass {
public:
MyClass () : errorVariable() {};

private:
MyClassData errorVariable;
}
and then I modify function:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)

while (it.hasNext())
{
const MyClassData &data = it.next();

if (data are ok)
return data;
}

return errorVariable;
}

But I'm not sure whether I like the idea of creating additional variable
just as placeholder for something which doesn't really exist..
Is there another way?

thx
d.
Hello,

One option is to use pointers and return NULL if you can't find it in
that list.
Other option is to return as const reference parameter and return a
true/false value if found or not.

Best regards,
asterisc

May 17 '07 #5
If you dont wanna have a class member like that, or dont wanna return
MyClassData() just to make it compile, how about something like this?

int MyClass (const MyClassData*& aReturnedObject)
{
QListIterator<MyClassDatait(fancylist)
while (it.hasNext())
{
const MyClassData &data = it.next();
if (data are ok)
// return data;
aReturnedObject = data;
return SUCCESS;
}
// return MyClassData();
aReturnedObject = NULL;
return NOT_FOUND;

}

May 17 '07 #6
Jim Langston wrote:
I used throw as thus:

CPlayer& FindPlayer( const SOCKET Socket )
{
// Get a reference in the map for this player
map_player::iterator it = World.ConnectedPlayers.find( Socket );
if ( it != World.ConnectedPlayers.end() )
return (*it).second;
else
throw 0;
}
Just a note, throwing 0 is a bad habit. Create a suitable exception
class, with some string that gives you the explanation of the error, and
throw that.

Regards,

Zeppe
May 17 '07 #7
RainBow wrote:
If you dont wanna have a class member like that, or dont wanna return
MyClassData() just to make it compile, how about something like this?

int MyClass (const MyClassData*& aReturnedObject)
That's a C-based approach and I would avoid it. Better to return a
pointer, and only if the performances are REALLY an issue. Otherwise,
throwing is always better: it's difficult to ignore an error condition
with something is thrown :)

Regards,

Zeppe
May 17 '07 #8
On Wed, 16 May 2007 21:18:04 -0400, "Victor Bazarov" wrote:
>Your class can have a static instance of itself, something like

class MyClass {
public:
...
static MyClassData errorVariable;
};
// mutable statics are out of fashion
static const MyClassData errorVariable;
>...
MyClassData MyClass::errorVariable;
...

if (data are ok)
return data;
else
return errorVariable;

...
if (&returnValueFromFunction == &errorVariable)
or a static member function:

static bool isError (const MyClassData& d);

If MyClassData becomes a friend of MyClass is needs no public funtions
or data.
>But it's better to 'try-catch' and 'throw'.
Depending on the context also a Null Object
(http://www.two-sdg.demon.co.uk/curbr...NullObject.pdf)
may be used.
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
May 17 '07 #9
Dear All,
thanks for all these interesting responses. I'm not sure thether
try/catch is really suitable for that. Correct me if I'm wrong but
I though that this construction is used when there is really an error.
But the example what I propose should return 'nothing' if not found and
'something' if found. However, this is not an error condition. It is
working state which means simply 'searching failed, do something about
it'. For the moment I have it realized with pointers, but I try to
convert my soft into pure referencing if possible....

d.
May 17 '07 #10
Ok, I just see that when asking, I named the variable as 'error'.. This
is of course misleading. It is not error, instead 'empty' should be used

Dejfson napsal(a):
Dear All,
thanks for all these interesting responses. I'm not sure thether
try/catch is really suitable for that. Correct me if I'm wrong but
I though that this construction is used when there is really an error.
But the example what I propose should return 'nothing' if not found and
'something' if found. However, this is not an error condition. It is
working state which means simply 'searching failed, do something about
it'. For the moment I have it realized with pointers, but I try to
convert my soft into pure referencing if possible....

d.
May 17 '07 #11
Dejfson wrote:
thanks for all these interesting responses. I'm not sure thether
try/catch is really suitable for that. Correct me if I'm wrong but
I though that this construction is used when there is really an error.
But the example what I propose should return 'nothing' if not found
and 'something' if found. However, this is not an error condition. It
is working state which means simply 'searching failed, do something
about it'. For the moment I have it realized with pointers, but I try
to convert my soft into pure referencing if possible....
The best analogy with returning "nothing" I can think of is 'std::find'
that returns the 'end' iterator if nothing is found. It's not "null",
nor is it a reference. It's a value you pass in, and it serves two
purposes: to indicate the end of the sequence and to allow returing of
"not found" condition. You might want to think of passing something in
(something you would consider "nothing") so that the function could
return it if it needs to... Anyway, good luck!

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 17 '07 #12
Hi Viktor,
this is I think exactly what i'm looking for. Have to study sources a
bit...
thanks to all
d.

May 17 '07 #13
I V
On Thu, 17 May 2007 01:52:48 +0200, Dejfson wrote:
Dear All,
can someone clarify me how to return the reference to the empty object
in case of error?
You could consider boost::optional<T>, which represents either a value of
type T, or nothing. See:

http://www.boost.org/libs/optional/doc/optional.html
May 18 '07 #14
Dejfson wrote:
can someone clarify me how to return the reference to the empty object
in case of error?
A reference can designate any kind of object, even an empty
collection. But more likely, what you are looking for is how to
return a reference to nothing.

The answer is, of course, that you can't. That's what pointers
(and null pointers) are for.
_not working_ Example of what i'd like to do:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)
while (it.hasNext())
{
const MyClassData &data = it.next();
if (data are ok)
return data;
}
return MyClassData();
}
This compiles, but of course it returns invalid reference in the case
when I don't find any suitable data. It there a way how to use the
reference in such case??
No. Is there any reason not to use a pointer?
I have just one solution in my mind: if I create class variable:
class MyClass {
public:
MyClass () : errorVariable() {};

private:
MyClassData errorVariable;
}
and then I modify function:
const MyClassData& MyClass ()
{
QListIterator<MyClassDatait(fancylist)
while (it.hasNext())
{
const MyClassData &data = it.next();
if (data are ok)
return data;
}
return errorVariable;
}
But I'm not sure whether I like the idea of creating
additional variable just as placeholder for something which
doesn't really exist..
It depends. This is a very valid solution in the case where the
reference is to a polymorphic base class; no need to test
anything, just arrange for the error class to have the desired
behavior (e.g. output an error message to std::cerr, throw an
exception, whatever). I agree that it's generally not really
indicated for value classes, however (and a name with Data in it
certainly suggests value semantics).

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 18 '07 #15
On May 17, 3:18 am, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Dejfson wrote:
can someone clarify me how to return the reference to the
empty object in case of error?
throw.
That's highly debatable. He didn't give any indication which
would make me suppose that the error condition is exceptional,
or that it could not generally be handled immediately in the
calling function. So throw looks like a bad design decision.
...
if (&returnValueFromFunction == &errorVariable)
But it's better to 'try-catch' and 'throw'.
Only if he can be relatively sure that the calling function will
not be able to process the error.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 18 '07 #16
On May 17, 10:48 am, Zeppe
<zeppe@.remove.all.this.long.comment.email.itwrote :
Jim Langston wrote:
I used throw as thus:
CPlayer& FindPlayer( const SOCKET Socket )
{
// Get a reference in the map for this player
map_player::iterator it = World.ConnectedPlayers.find( Socket );
if ( it != World.ConnectedPlayers.end() )
return (*it).second;
else
throw 0;
}
Just a note, throwing 0 is a bad habit.
And how. Does he expect the caller to use a "catch ( int )"?

What I'd like to know is what's wrong with simply:

CPlayer* FindPlayer( const SOCKET Socket )
{
// Get a reference in the map for this player
map_player::iterator it =
World.ConnectedPlayers.find( Socket );
return it == World.ConnectedPlayers.end()
? &it->second
: NULL ;
}

It's short and simple, and about the easiest solution to
understand.
Create a suitable exception class, with some string that gives
you the explanation of the error, and throw that.
If you have to throw. Throwing should generally be reserved for
exceptional cases.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 18 '07 #17
On May 17, 10:50 am, Zeppe
<zeppe@.remove.all.this.long.comment.email.itwrote :
RainBow wrote:
If you dont wanna have a class member like that, or dont wanna return
MyClassData() just to make it compile, how about something like this?
int MyClass (const MyClassData*& aReturnedObject)
That's a C-based approach and I would avoid it. Better to return a
pointer, and only if the performances are REALLY an issue.
Better to return a pointer, even in C.
Otherwise, throwing is always better:
Throwing is rarely the best solution. Only when it is certain
that the error is really exceptional, and cannot be handled in
the layer immediately above the function in the call stack, or
in a constructor, to avoid the necessity of creating the an
invalid object (and thus having to constantly test state).
it's difficult to ignore an error condition
with something is thrown :)
The Java libraries seem to do it quite well:-).

It's even more difficult to ignore a well designed return code.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 18 '07 #18
James Kanze wrote:
What I'd like to know is what's wrong with simply:

CPlayer* FindPlayer( const SOCKET Socket )
{
// Get a reference in the map for this player
map_player::iterator it =
World.ConnectedPlayers.find( Socket );
return it == World.ConnectedPlayers.end()
? &it->second
: NULL ;
}

It's short and simple, and about the easiest solution to
understand.
>Create a suitable exception class, with some string that gives
you the explanation of the error, and throw that.

If you have to throw. Throwing should generally be reserved for
exceptional cases.
Exactly. Exceptional given the semantic of an operation. For a function
that is called "FindPlayer" I definitely won't expect any exception to
be thrown if the player is not found. Differently, for a function like
"GetPlayer(PlayerID id)" I would usually consider the absence of that
player a good candidate for an exception to be thrown :)

Regards,

Zeppe
May 18 '07 #19

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

Similar topics

7
by: Pablo J Royo | last post by:
Hello: i have a function that reads a file as an argument and returns a reference to an object that contains some information obtained from the file: FData &ReadFile(string FilePath); But ,...
12
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...
4
by: Gerry Abbott | last post by:
Hi All, Im trying to use thie combination but have not had success. Below is the function It tried the following myriskLevel(2,2) myrisklevel(0,0,2) and the ismissing(Three) alwasy...
4
by: Jon Skeet | last post by:
I've just noticed something rather odd and disturbing. The following code displays "True": using System; class Test { public static void Main(string args) { string x = new string...
14
by: Mike Labosh | last post by:
How do you define whether the return value of a function is ByRef or ByVal? I have a utility class that cleans imported records by doing *really heavy* string manipulation in lots of different...
6
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...
27
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1...
5
by: Frank Hauptlorenz | last post by:
Hello, I recognized some days ago, that returning a DataTable blocks my WCF-Service. Is this a known bug? If I add this table to a new DataSet() and return this, it works. Thank you, Frank
5
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.