2

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.

1 Answers1

3

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.

Timbo
  • 27,472
  • 11
  • 50
  • 75
  • But how would I know IF the constructor will succeed. IMO the only way to know if a constructor has succeeded is by checking if the auto_ptr to which the new object is being assigned is not null. Is there any other way to know if the constructor has succeeded (when i m in the constructor)? –  Feb 17 '11 at 19:57
  • When you are inside the constructor you know whether it succeeded or not. It is your code inside there, isn't it? – Timbo Feb 17 '11 at 20:59