在没有std::nothrow的构造函数中克服std::bad_alloc



假设我有一个类如下:

Class A{
private:
int* A1;
int* A2;
public:
A(): A1(new int[1000]), A2(new int[1000]){}         
~A(){delete[] A1; delete[] A2;}
}

我想处理这样一种情况:第一次分配成功,第二次分配失败,并且抛出std::bad_alloc

据我所知,析构函数不会被调用,因为对象没有成功创建。

如果我改为这样做,这是可以解决的:

A(): A1(new int[1000]), A2(new(nothrow) int[1000]){} 

那我就可以毫无例外地处理这个案子了。

然而,据我所知,nothrow很少被使用。我不知道在这种情况下如何使用异常。

非常感谢。

我会使用std::unique_ptr

class A {
std::unique_ptr<int[]> A1, A2;
public:
A() : A1(std::make_unique_for_overwrite<int[]>(1000)), A2(std::make_unique_for_overwrite<int[]>(1000)) { }
// if A1 succeeds and A2 fails, A1 is freed
// default no-body destructor works fine
};

但是,如果你真的想要原始指针,你可以将逻辑压缩成一系列委托构造函数。

class A {
int *A1, *A2;
A(int *A1) try : A1(A1), A2(new int[1000]) { }
catch(...) { delete[] A1; } // handle A2 fails but A1 success; automatically rethrows (note: accessing members in this catch clause is UB, but we have the constructor parameter)
public:
A() : A(new int[1000]) { }
// any exception in first allocation is immediately thrown here
// any exception in second allocation bubbles up through here after being rethrown
~A() { delete[] A1; delete[] A2; }
};

最新更新