Object Array Initialization without Default Constructor
When attempting to initialize an array of objects that lack a default constructor, programmers often encounter the error "X::X() is private within this context". This error arises because the default constructor is typically set to private to prevent unintentional object creation.
One solution is to employ placement-new, a low-level C operator that allows objects to be constructed directly into a block of memory. Here's an example:
class Car { int _no; public: Car(int no) : _no(no) // Initialize _no directly { } }; int main() { int userInput = 10; void *rawMemory = operator new[](userInput * sizeof(Car)); // Allocate raw memory Car *myCars = static_cast<Car *>(rawMemory); // Cast to Car * for (int i = 0; i < userInput; ++i) { new(&myCars[i]) Car(i); // Construct Car objects in-place using placement-new } // Destruct objects in reverse order for (int i = userInput - 1; i >= 0; --i) { myCars[i].~Car(); // Destroy the object using placement-delete } operator delete[](rawMemory); // Release raw memory return 0; }
This technique provides a way to initialize arrays of objects without modifying the constructor's access specifier. It adheres to best practices by avoiding unnecessary default constructors while enabling flexible and efficient object creation.
The above is the detailed content of How to Initialize an Array of Objects Without a Default Constructor in C ?. For more information, please follow other related articles on the PHP Chinese website!