> > > What is the best way to create functions that, based on some input,
return either structures or a null value
if the structure cannot be made?
The problem is that the structure has be created inside the function,
and I've heard that returning a pointer to a locally created structure
is unsafe.
struct X { /* . . . */ };
X f(void) {
X x;
// modify x
return x;
}
This is the safest *and* most efficient way.
You can invoke it like this:
X x = f();
and *no* copies will be required if your C++ compiler implements
the Named Return Value Optimization (NRVO).
What about the requirement to return something different (like 0)
to indicate the object creation is impossible?
The OP specified an impossible combination of events. There are
(to my mind) 3 ways of resolving this:
1) relax the requirement for a struct to be returned
2) relax the requirement for NULL to be returned
3) return both in a std::pair<> or similar
Trollsdale answered number (2) with (surprisingly) a mostly
correct answer, if you ignore his extraneous use of
the dereference operator.
One could augment his answer by giving X a flag, or some such,
indicating whether there was an error condition.
Note that the OP's other requirement "if a structure cannot be made"
is also unlikely, because either a struct is constructible
or it isn't (perhaps the OP meant, "if some error condition occurs").
Other posters on the the thread have answered (1) (with suggestions
like returning a pointer, or filling out a reference-to-struct
passed as parameter).