Auto_ptr deallocating object because of an unconstructed object

Hi,

I have the following piece of code -

foo(Auto_ptr<A> autop1){
Auto_ptr<B>autop2(new B(10, autop1, 40));
// some code
autop1.callFunc(); >>> segmentation fault
}

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 but the initialization step seems to have gone till _var2. So 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.

My question is
- how can I avoid this problem?
- Is there a safe method to pass around auto_ptr's between functions.
http://www.cplusplus.com/reference/std/memory/auto_ptr/auto_ptr/ the value was not destroyed, the ownership was lost (it was passed to autop2::_var2)

What do you want to accomplish?
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.

For example -

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.
new never returns NULL unless you use the nothrow version of new, which nobody does. Therefore
your "segmentation fault" line is completely useless.
Our code base uses the no throw version of new.
Simply put I want the calling function to still have the ownership of the pointer if the callee constructor could not create an object. Is there a way to do it?
If foo() is never to own the auto_ptr (but B is) then foo should take the auto_ptr by reference.

BTW, your example code above is using the throwing version.

Topic archived. No new replies allowed.