It is a problem to assume that a default constructor for a class is defined and then an array of objects of that class will be constructed. This will enable the new operator to break the code.
First, allocate memory, and then call the constructor object to allocate memory. Code to make a simple memo.
A class that does not have a constructor defined cannot define an array of objects of that 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 () {}};// Classes that do not have a constructor defined will fail when the array is defined. 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 (); Destructors are only called at each location, but no memory is freed operator Delete[] (PA); Release Memory//delete [] PA; Suppose Class A does not define a constructor. Then this sentence is correct. But once the constructor is defined, the memory is wrong. Only through operator delete to remove operator new allocated space, see the previous sentence//But the following method is not related to 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; Built-in type no destructor, direct delete can void *raw3 = OperaTor New [] (sizeof (int)); 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;}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
How to define an array of objects without a default constructor