Re: try block in constructor initialization
On 11 Dez., 07:23, AlfC <alfredo.cor...@gmail.com> wrote:
BTW, if A is the only access to H1/H2, I
am not sure whether to make class A a friend of H1 and H2. Is this a
good idea?
It seems appropriate in this situation. This combination of H* in
A is somewhat similar to the bridge pattern and often (but not
always) the pimpl container has special access rights to it's
implementation pointer.
I like the solution because it doesn't use assignment and retains the
constrains of H1/H2 in their constructors. (provided that maintaining
the constrains of H1/H2 in their constructors is a good idea at all.)
Your example is of-course somewhat artifical, but it is a
valid question to ask the following: If the precondition of H1
is *not* fulfilled, is this a programmers error or a normal
use case? A class - like H1 - has to provide it's preconditions
for valid construction and it seems maybe astonishing that
failing to construct H1 ends in H2 construction (there maybe
other reasons why H1 failed, which might have not been
foreseen). If H2 is some kind of "emergency exit" independent
from the actual error cause, this might be a reasonable
approach, on the other hand. Since we already recognized
that A might have special access rights to H1 and H2,
you could provide support for A in H1:
class H1 : public H {
friend class A;
static bool isFeasible(int a) {
return a != 0;
}
H1(int a) : a_(a){ if (!isFeasible(a)) throw something();}
int a_;
};
....
class A{
static H* create(int a) {
if (H1::isFeasible(a))
return new H1(a);
else
return new H2();
}
A(int a) : impl_(create(a)) {}
std::auto_ptr<H> impl_;
};
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]