pointers and references to automatic variables :( how to do a good builder pattern implementation?
sorry for the long subject, but I didnt know how to summarize the
problem
as you know, a C++ programmer has to avoid the classical "returing a
pointer or reference to local storage":
MyClass & bad()
{
MyClass result = some computation;
return result;
}
a good code review can get rid of that, but my problem is more subtle.
here is an example:
void whatever()
{
MyInterface * blah;
MyDerived1 a;
MyDerived2 b;
if( some computation ) {
blah = &a;
} else {
other computation
blah = &b;
}
blah->execute();
}
that was a horrible piece of code, but valid and correct. the sad part
is I?ve seen a similar code with a slight modification:
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();
}
I hate those silent bugs. these devils make the code work on many
tests and fail right in the front of client :(
a question is, should I have to switch to free store, instead of using
automatic storage? (remember first example works fine with automatic
storage)
but all of this was an introduction to the real problem: implementing
a class following the builder design pattern
a code example will show more than 1000 words:
void illonaStaller()
{
MovieBuilder movie(xxx);
Actor peterNorth;
Actress moanaPozzi;
if( some computation ) {
movie.putInScene(peterNorth);
} else {
other computation
movie.putInScene(moanaPozzi);
}
...
movie.build(couchScene);
}
this code will not have problems since all objects are in the same
scope, but if the build uses lazy evaluation (MovieBuilder::putInScene
could just store pointers to the parameters to be evaluated only by
MovieBuilder::build), we will run into the same problems presented on
the second example
so, what is a good builder implementation?
1) using references/pointers and trust the client code?
2) always copy the parameters (and pay the cost of copying huge
objects... non-copyables will be denied)
3) switch to freestore (we have to control ownership... perhaps using
auto_ptr or shared_ptr as parameters should help)
I have more comments about that, but I think I am too biased and I am
sure your thoughts will help me to achieve a good balance of choices
Diego
HP
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]