I have a class A that allocates memory in its constructor using new.
What happens when I allocate a chunk of As and (while new[] is initializing the single As) one of them throws std::bad_alloc in their constructor?
Does operator new[] destruct the already initialized objects?
Or is it my duty to make sure the constructor doesn’t throw?
EDIT: The two invocations of new might sound confusing, so here’s a piece of code to clarify:
class A
{
int* mem;
public:
A()
{
try
{
mem = new int[3];
}
catch(bad_alloc&)
{
throw 5;
}
}
~A()
{
delete[] mem;
}
}
A* list = 0;
try
{
list = new A[50000];
}
catch(int)
{
// When I get here, did the new[] above call the destructors
// of all the objects it managed to construct before one of them threw?
}
If you do
new Foo()and the constructor ofFoothrows, then the memory allocated by the relevantoperator newwill be freed. And if the constructor for any member of Foo has succeeded, that member’s destructor will be called.If you do
new Foo[100], and the 42nd constructor throws, then all the already-constructed Foo objects are destroyed (in reverse order).