12

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?

wahab
  • 767
  • 1
  • 5
  • 22
  • 9
    No. This is what the technique known as [RAII](https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) is useful for. If you want a class for managing a dynamic array, it is called [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). Don't try to write one yourself. – BoBTFish Feb 25 '16 at 14:15
  • 2
    Required reading: [Why should C++ programmers minimize use of 'new'?](http://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – Cody Gray Feb 25 '16 at 14:18
  • 2
    Besides the use of `std::vector`, if the size is a compile-time fixed constant, and the memory don't have to allocated from the heap, consider the use of [`std::array`](http://en.cppreference.com/w/cpp/container/array) instead. – Some programmer dude Feb 25 '16 at 14:19
  • The question should show the types of `a`, `b` and `c`, and you should also clarify whether you mean to ask if the memory will be freed. – M.M Feb 26 '16 at 06:36

4 Answers4

14

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.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
9

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.

Pete Becker
  • 69,019
  • 6
  • 64
  • 147
3

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.

Community
  • 1
  • 1
Simple
  • 12,634
  • 2
  • 38
  • 43
1

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[].