I am writting a method returning a double*. However, I would like to base another method behavior on output from this method. I would like to have
if (methodReturningArray()==0)
{
this_behavior();
}
else
{
this_other_behavior(methodReturningArray());
}
Is it appropriate then to have methodReturningArray() returning either the ‘initialized’ or ‘build’ double* and if this double* could not be appropriately be initialized or build, returning like that
double* new_array ;
return new_array ;
?
In other words, the double* output plays also role of a boolean to check whether some property is completed so that the double* output can be built.
Thanks and regards.
To indicate that something that you return by pointer has not been initialized, use
return NULL. And check for it withif(double* d = method())(or in any other fashion you like).However, this is not your (or my) grandfathers C++ and you should only write something like this, when you absolutely have reason to do so. I would prefer to return either a
std::arrayorstd::vectorby value wrapped and throw an exception if the behavior that leads to initialization failure is somehow exceptional. If failing to initialize is part of the idea I’d wrap the return value in aboost::optional. But probably I’d write something that takes anOutputIteratorto not force any particular container on my client.Notes on disaster:
double* d; return dwill leave your client with a pointer that points to random memory. There is no way for her to figure out if has to bedeleted[]or if it is valid. Always initialize your pointers.Code snippets: