Allocating memory in constructors
Is it okay to use new
inside a constructor to allocate memory for my class?
Yes, it's perfectly fine and common to allocate memory using new
inside a constructor. This is often necessary when the amount of memory needed is not known at compile time.
Here's an example:
#include <iostream>
class MyClass {
private:
int* data;
size_t size;
public:
MyClass(size_t size) : size(size) {
data = new int[size];
}
~MyClass() {
delete[] data;
}
};
int main() {
MyClass obj(10);
}
However, there are a few important things to keep in mind:
- If you allocate memory in the constructor, you must deallocate it in the destructor to avoid memory leaks.
- If your constructor can throw exceptions, you need to be careful. If an exception is thrown after you've allocated memory but before the constructor completes, your destructor won't be called. This can lead to memory leaks. One solution is to use smart pointers, which we'll cover in a future lesson.
- Allocating memory in the constructor can make your class more difficult to reason about and maintain. Where possible, consider using standard library containers like
std::vector
instead of managing memory manually.
Dynamic Memory and the Free Store
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete