I want to be able to pass an auto_ptr as an argument to a constructor. But if the new object could not be created (probably bcoz of no memory), then I want the original auto_ptr to be able to retain its value.
Eg:
foo (Auto_ptr<A> autop1) {
Auto_ptr<B> autop2(new B(10, autop1, 40));
if (!autop2.get()) autop1.callFunc(); >>> segmentation fault; But I want to do this!
}
Class B{
public:
B(int var1, Auto_ptr<A> var2, int var3):
_var1(var1), _var2(var2), _var3(var3){ }
private:
int _var1, _var3;
Auto_ptr<A> _var3;
}
In function foo(), the new object B was not created due to lack of memory and the autop1 value was destroyed when the new operator returned without creating the object. And when we try to access autop1, it results in a seg fault. What is a good way to avoid this problem. Its okay if a new object was created and the ownership was passed to its member variables. I want to be able to use autop1 in foo() if a new B object could not be created and autop2 would have NULL.
You could pass the auto_ptr to the constructor of
B
by reference, and only assign it to the member variable when you know the constructor will succeed.