Re: pointers and references to automatic variables :( how to do a good builder pattern implementation?
On Jul 31, 5:51 am, Diego Martins <jose.di...@gmail.com> wrote:
[want best fix for...]
void whateverUB()
{
MyInterface * blah;
if( some computation ) {
MyDerived1 a(parameters depending of computation);
blah = &a;
} else {
other computation
MyDerived2 b(other parameters depending of other computation);
blah = &b;
}
blah->execute();
}
One simple solution is:
if( some computation ) {
MyDerived1 a(parameters depending of computation);
a->execute();
} else {
other computation
MyDerived2 b(other stuff);
b->execute();
}
If there are many common things done with "blah", then move them into
a function:
if( some computation ) {
MyDerived1 a(parameters depending of computation);
execute_and_more(a);
} else {
other computation
MyDerived2 b(other stuff);
execute_and_more(b);
}
Or turning things upside down you could have a factory method, but
then you're using the heap unnecessarily.
Working from the principle of least-invasive solution, I can imagine a
templated type that reserves stack storage but doesn't necessarily
contain a constructed object, ala:
might_become<MyDerived1> a;
might_become<MyDerived2> b;
MyInterface * blah;
if( some computation ) {
a.construct(parameters depending of computation);
blah = &*a;
} else {
other computation
b.construct(other stuff);
blah &*b;
}
blah->execute();
I have only very briefly looked at it so am not sure, but perhaps
boost::optional would fit the bill?
As you say, shared pointers are another possibility. You could also
hack around with alloca, booleans and/or NULLs to track where you've
got to. Painful.
If the objects really are large, perhaps give them value semantics,
employing internal reference counting or alternative....
Cheers,
Tony
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]