Object Array Initialization Without Default Constructor
In C , when creating an array of objects, the default constructor is called to initialize each element. However, in some cases, you may encounter an error when initializing an array of objects if the default constructor is private or doesn't exist.
To overcome this, you can employ the technique of placement-new, which provides a way to initialize objects in situ, without invoking the default constructor.
Here's how you can use placement-new to initialize an array of objects without a default constructor:
class Car { private: int _no; public: Car(int no) : _no(no) {} }; int main() { void *raw_memory = operator new[](NUM_CARS * sizeof(Car)); Car *ptr = static_cast<Car *>(raw_memory); for (int i = 0; i < NUM_CARS; ++i) { new(&ptr[i]) Car(i); } // destruct in inverse order for (int i = NUM_CARS - 1; i >= 0; --i) { ptr[i].~Car(); } operator delete[](raw_memory); return 0; }
In this code, raw_memory represents the raw memory block used to store the array of Car objects. We then cast it to a Car * pointer and use placement-new to construct each object in place, initializing it with the specified number.
When you're done with the array, remember to destruct the objects in reverse order and delete the raw memory allocated using placement-new. This approach allows you to initialize an array of objects even if their default constructor is inaccessible.
The above is the detailed content of How to Initialize an Object Array in C Without a Default Constructor?. For more information, please follow other related articles on the PHP Chinese website!