John Goche skrev:
Hello,
I would like fooBar to be initialized to zero in the following scenario
where there is not enough memory to complete construction after
an object of sizeof(FooBar) has been allocated on the heap. Is
the standard way to deal with this situation in plain old standard
C++ to use a try catch block in main() and a throw inside the
constructor after cleaning up or can anyone suggest alternatives?
The first thing to do is ask yourself why you use raw pointers. You
should realise that as soon as you unconditionally delete the pointers
in the destructor is that the (implied) copy constructor and assignment
operator suddenly does not work. Assuming you disable these, one
solution could be std::auto_ptr:
>
Thanks,
JG
class FooBar {
public:
FooBar();
private:
Foo *foo;
Bar *bar;
}
FooBar::FooBar() {
foo = new Foo(); // successful
bar = new Bar(); // unsuccessful
std::auto_ptr<Fooautofoo(new Foo());
std::auto_ptr<Barautobar(new Bar());
foo = autofoo.reset();
bar = autobar.reset();
}
>
int main() {
FooBar *fooBar = new FooBar();
No reason to use new here. Watch out for the Java syndrome! Perhaps
pointers aren't really appropriate for your solution and again - if yo
need a pointer in your class, quite probably it should not be raw.
/Peter