Re: NULL
On Jun 22, 12:33 pm, Mohitz <coolmoh...@gmail.com> wrote:
i am not quite good with pointers. Here is the code i am using. Is
something wrong with it?
ClassName * funcName(string name)
{
deque<ClassName> tempDeque = someGlobalClassNameDeque;
deque<ClassName>::iterator tempDequeIterate;
tempDequeIterate = tempDeque.begin();
while (tempDequeIterate != tempDeque.end())
{
ClassName * tempClassName = new ClassName();
ClassName temp = *tempDequeIterate;
*tempClassName = temp;
if (name == temp->name)
return tempClassName;
tempDequeIterate++;
}
return NULL;
}
Yes, it is revolting. The following code has exactly
the same effect (some var names shortened so that my
code fits in Usenet line limits):
for( deque<ClassName>::const_iterator it = global.begin();
it != global.end(); ++it )
{
if ( name == it->name )
return new ClassName(*it);
}
return NULL;
Having said that, this is a poor method to solve
your problem. In fact even your seemingly simple
invocation of it has an error:
ClassName * p = funcName(someString);
if (p == NULL)
parseError(someString + " undefined.");
else
toRet = anotherFunc(*p);
return toRet;
You never deleted the objected allocated by 'new'.
Also if p were NULL then you return a value that
you never set.
The good solutions to your problem are:
1) throw an exception on failure
2) return a ClassName with a special value
that indicates failure.
With exceptions the above code becomes:
ClassName funcName(string name)
{
for( deque<ClassName>::const_iterator it = global.begin();
it != global.end(); ++it )
{
if ( name == it->name )
return *it;
}
throw std::runtime_error( name + " undefined." );
}
//
// In main function or whatever
//
try {
return anotherFunc( funcName(someString) );
}
catch (std::exception &e) {
parseError( e.what() );
return whatever;
}
Much simpler!