Re: function returning reference to empty object
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<MyClassData> it(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<MyClassData> it(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:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34