Passing auto_ptr as an argument to the constructor

I want to pass auto_ptr as an argument to the constructor. But if a new object cannot be created (possibly bcoz without memory), then I want the original auto_ptr to be able to save its value.

For instance:

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 the foo () function, a new B object was not created due to lack of memory, and the autop1 value was destroyed when the new statement returned without creating the object. And when we try to access autop1, this leads to a seg error. What is a good way to avoid this problem. This is normal if a new facility was created and ownership was transferred to its member variables. I want to be able to use autop1 in foo () if a new B object cannot be created and autop2 is NULL.

+3
1

auto_ptr B -, , .

+3

Source: https://habr.com/ru/post/1792741/


All Articles