wahab
wahab

Reputation: 835

Memory Allocation Exception in Constructor

I have a constructor that allocates several blocks of memory using the new operator.

X::X() {
    a = new int[100];
    b = new char[100];
    c = new float[100];
}

My question is, if the allocation of c fails, and the constructor throws an exception, will the memory for a and b be automatically freed?

Upvotes: 12

Views: 1444

Answers (4)

Bathsheba
Bathsheba

Reputation: 234875

The memory to which a and b point would not be automatically freed. Every new[] must be balanced explicitly with a delete[].

Even if your destructor performed the deletion (assuming a, b, and c are class members), then you'd still leak memory. That's because the destructor wouldn't be called in this case since the object failed to construct.

Using std::vectors would obviate these problems.

Upvotes: 14

Pete Becker
Pete Becker

Reputation: 76523

a, b, and c will all be destroyed. Depending on what types they are, that might or might not release the memory. If they are pointers their destructors don't do anything, and the memory leaks. If they are some sort of smart pointer, presumably their destructors will release the memory.

Upvotes: 9

Chandra Bhushan
Chandra Bhushan

Reputation: 19

Variable a and b will not be automatically destroyed for sure. In your case you must use this std::vector. This is because whenever we use a new[] operator for that we need to explicitly define a delete[].

Upvotes: 1

Simple
Simple

Reputation: 14420

No they won't. This is why you need to learn about RAII and in particular, containers and smart pointers.

In your case, you can use std::vector<T> instead of new T[100], for example.

Upvotes: 3

Related Questions