Allocating an Array of Objects Dynamically
When working with objects that contain dynamically allocated arrays, creating an entire array of these objects can present challenges. Using a simple approach like:
A* arrayOfAs = new A[5]; for (int i = 0; i < 5; ++i) { arrayOfAs[i] = A(3); }
leads to memory issues as the A objects destructed within the loop delete their internal myArray arrays, rendering the array elements of arrayOfAs invalid.
To avoid these issues, understanding the "rule of 4" (or the extended "rule of 5" in C 11) is crucial for classes containing raw pointers:
If not defined, the compiler generates its own versions of these methods, which may not be suitable for raw pointers.
To resolve the aforementioned error, the minimum requirements for a class containing a pointer to an array include:
class A { size_t mSize; int* mArray; public: A(size_t s = 0) {mSize=s;mArray = new int[mSize];} ~A() {delete [] mArray;} A(A const& copy) { mSize = copy.mSize; mArray = new int[copy.mSize]; // Handle copying of integers/other members } A& operator=(A other) { std::swap(mArray, other.mArray); std::swap(mSize, other.mSize); return *this; } };
Alternatively, using standard containers like std::vector can simplify the process, as they handle memory management automatically:
class A { std::vector<int> mArray; public: A(){} A(size_t s) :mArray(s) {} };
The above is the detailed content of How to Avoid Memory Issues When Dynamically Allocating an Array of Objects in C ?. For more information, please follow other related articles on the PHP Chinese website!