Object Array Initialization without Default Constructor
Consider the following code:
#include <iostream> class Car { private: Car(){}; int _no; public: Car(int no) { _no=no; } void printNo() { std::cout<<_no<<std::endl; } }; void printCarNumbers(Car *cars, int length) { for(int i = 0; i<length;i++) std::cout<<cars[i].printNo(); } int main() { int userInput = 10; Car *mycars = new Car[userInput]; for(int i =0;i < userInput;i++) mycars[i]=new Car[i+1]; printCarNumbers(mycars,userInput); return 0; }
This code aims to create an array of cars, but when compiled, it encounters an error stating that the Car() constructor is private. The question is, can the initialization be performed without making the Car() constructor public?
Solution
To address this issue, placement-new can be utilized as follows:
class Car { 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; }
Placement-new allows memory to be allocated and an object to be constructed at a specific location. In this case, raw_memory is allocated, and then placement-new is used to construct Car objects at the addresses pointed to by ptr.
By leveraging placement-new, the initialization of the array of cars can be achieved while respecting the privacy of the Car() constructor
The above is the detailed content of Can Object Array Initialization Be Achieved Without a Public Default Constructor?. For more information, please follow other related articles on the PHP Chinese website!