If a class does not define the default constructor, constructing the object array of the class will be a problem. So we implemented a code that opened the new operator. First, allocate the memory, and then call the constructor to construct the object on the allocated memory. The following code provides a simple memo.
// The class without a constructor cannot define the object array of the class, except for built-in types, // operator New + ctor // dtor + operator Delete // operator new [] + ctor // dtor + operator Delete [] # include <bits/stdc ++. h> using namespace STD; Class A {PRIVATE: int X; public: A (INT _ x): X (_ x ){}~ A () {}}; // a class without a defined constructor may encounter problems when defining arrays !! Int main () {// A VECs [10]; // compile failed // Method 1: placement new void * Raw = Operator new [] (3 * sizeof (a); A * pA = static_cast <A *> (raw); For (INT I = 0; I <3; ++ I) New (& pa [I]) a (I); // placement new // destructor + deallocate for (INT I = 0; I <3; ++ I) Pa [I]. ~ A (); // only the Destructor is called at each location, but the memory operator Delete [] (PA) is not released; // The memory is released // Delete [] Pa; // if Class A does not define the constructor, this sentence is correct, but the memory is wrong once the constructor is defined. You can only delete the space allocated by operator new through operator Delete, see the previous sentence // but the following method does not have to do with whether to define the constructor !! Void * raw2 = Operator new (sizeof (INT); int * P = static_cast <int *> (raw2); New (p) int (3 ); cout <* P <Endl; Delete P; // There is no destructor in the built-in type. Directly Delete void * raw3 = Operator new [] (sizeof (INT) * 3); int * pints = static_cast <int *> (raw3); For (INT I = 0; I <3; ++ I) new (& (pints [I]) int (I); // placement New for (INT I = 0; I <3; ++ I) cout <pints [I] <Endl; operator Delete [] (pints); Return 0 ;}
No default constructor. How to define an array of objects?